Skip to content

Beeswarm

Creates a beeswarm from an array of data: each circle sits at its value along the axis set by x (or y), packed beside its neighbors so none overlap. Set the other axis to a categorical key to draw one swarm per category. Any Plot can switch between a scatter and a beeswarm with swarm; see swarmConfig for spacing and overflow.

Each circle sits at its value along x and is nudged up or down just far enough to clear its neighbors, so dense values pile up into a shape that reads like a distribution while every point stays visible. The layout is deterministic: the same data always draws the same swarm.

const countries = (() => {
  let seed = 7;
  const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  const normal = () =>
    Math.sqrt(-2 * Math.log(random())) * Math.cos(2 * Math.PI * random());
  const regions = ["Africa", "Americas", "Asia", "Europe", "Oceania"];
  return Array.from({length: 180}, (_, i) => {
    const region = regions[i % 5];
    const income = Math.round(Math.exp(8.6 + 0.3 * (i % 5) + 0.8 * normal()));
    return {
      country: "Country " + (i + 1),
      region,
      "GDP per Capita": income,
      "Life Expectancy":
        Math.round((48 + 3 * Math.log(income) + 2.5 * normal()) * 10) / 10,
      Population: Math.round(Math.exp(15.5 + 1.3 * normal())),
    };
  });
})();

const config = {
  data: countries,
  groupBy: "country",
  x: "Life Expectancy",
};

Set the other axis to a categorical key and each category gets its own swarm, centered on its band. Swap x and y for vertical swarms.

const countries = (() => {
  let seed = 7;
  const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  const normal = () =>
    Math.sqrt(-2 * Math.log(random())) * Math.cos(2 * Math.PI * random());
  const regions = ["Africa", "Americas", "Asia", "Europe", "Oceania"];
  return Array.from({length: 180}, (_, i) => {
    const region = regions[i % 5];
    const income = Math.round(Math.exp(8.6 + 0.3 * (i % 5) + 0.8 * normal()));
    return {
      country: "Country " + (i + 1),
      region,
      "GDP per Capita": income,
      "Life Expectancy":
        Math.round((48 + 3 * Math.log(income) + 2.5 * normal()) * 10) / 10,
      Population: Math.round(Math.exp(15.5 + 1.3 * normal())),
    };
  });
})();

const config = {
  data: countries,
  groupBy: "country",
  color: "region",
  x: "Life Expectancy",
  y: "region",
};

With a numeric y and a categorical x, the swarms run vertically.

const countries = (() => {
  let seed = 7;
  const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  const normal = () =>
    Math.sqrt(-2 * Math.log(random())) * Math.cos(2 * Math.PI * random());
  const regions = ["Africa", "Americas", "Asia", "Europe", "Oceania"];
  return Array.from({length: 180}, (_, i) => {
    const region = regions[i % 5];
    const income = Math.round(Math.exp(8.6 + 0.3 * (i % 5) + 0.8 * normal()));
    return {
      country: "Country " + (i + 1),
      region,
      "GDP per Capita": income,
      "Life Expectancy":
        Math.round((48 + 3 * Math.log(income) + 2.5 * normal()) * 10) / 10,
      Population: Math.round(Math.exp(15.5 + 1.3 * normal())),
    };
  });
})();

const config = {
  data: countries,
  groupBy: "country",
  color: "region",
  x: "region",
  y: "Life Expectancy",
};

A size accessor scales each circle, and the packing respects every radius. When a swarm is too tall for its band, swarmConfig.overflow decides what gives: "shrink" (default) scales all circles down together, "clamp" keeps their sizes and holds the outliers at the band’s edge, and "visible" lets the swarm spill over.

const countries = (() => {
  let seed = 7;
  const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  const normal = () =>
    Math.sqrt(-2 * Math.log(random())) * Math.cos(2 * Math.PI * random());
  const regions = ["Africa", "Americas", "Asia", "Europe", "Oceania"];
  return Array.from({length: 180}, (_, i) => {
    const region = regions[i % 5];
    const income = Math.round(Math.exp(8.6 + 0.3 * (i % 5) + 0.8 * normal()));
    return {
      country: "Country " + (i + 1),
      region,
      "GDP per Capita": income,
      "Life Expectancy":
        Math.round((48 + 3 * Math.log(income) + 2.5 * normal()) * 10) / 10,
      Population: Math.round(Math.exp(15.5 + 1.3 * normal())),
    };
  });
})();

const config = {
  data: countries,
  groupBy: "country",
  color: "region",
  size: "Population",
  x: "GDP per Capita",
  y: "region",
};

swarm is a Plot option, so one chart can switch between a scatter and a beeswarm: set swarm to true and back. Each circle keeps its id, so it glides from its scatter position into the swarm and back. With swarm on, the y values are ignored and the y axis steps aside. Plot circles leave motion trails when they move; shapeConfig.Circle.trail: false turns them off for a clean glide.

const countries = (() => {
  let seed = 7;
  const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  const normal = () =>
    Math.sqrt(-2 * Math.log(random())) * Math.cos(2 * Math.PI * random());
  const regions = ["Africa", "Americas", "Asia", "Europe", "Oceania"];
  return Array.from({length: 180}, (_, i) => {
    const region = regions[i % 5];
    const income = Math.round(Math.exp(8.6 + 0.3 * (i % 5) + 0.8 * normal()));
    return {
      country: "Country " + (i + 1),
      region,
      "GDP per Capita": income,
      "Life Expectancy":
        Math.round((48 + 3 * Math.log(income) + 2.5 * normal()) * 10) / 10,
      Population: Math.round(Math.exp(15.5 + 1.3 * normal())),
    };
  });
})();

const config = {
  data: countries,
  groupBy: "country",
  color: "region",
  x: "GDP per Capita",
  y: "Life Expectancy",
  swarm: false,
  duration: 800,
  shapeConfig: {Circle: {trail: false}},
};

Configuration

import {Beeswarm} from "@d3plus/core";

Extends Plot → Viz.

activefalse | function

The active callback function for highlighting shapes.

annotationsunknownDefault unknown

Allows drawing custom shapes to be used as annotations in the provided x/y plot. This method accepts custom config objects for the Shape class, either a single config object or an array of config objects. Each config object requires an additional parameter, the "shape", which denotes which Shape sub-class to use (Rect, Line, etc).

Additionally, each config object can also contain an optional "layer" key, which defines whether the annotations will be displayed in "front" or in "back" of the primary visualization shapes. This value defaults to "back" if not present ("front" for callouts).

Three more kinds draw chart notes: "Callout" anchors wrapped text in a box at each data row's x/y (in data units, or plot-area fractions with xRef/yRef: "plot"), offset by dx/dy pixels and joined to its anchor by a connector ending in an arrowhead or dot (see CalloutAnnotation); "ReferenceLine" and "ReferenceBand" draw what referenceLines and referenceBands entries expand into. All annotations follow zoom and never respond to the pointer or keyboard.

axisPersistbooleanDefault unknown

Determines whether the x and y axes should have their scales persist while users filter the data, the timeline being the prime example (set this to true to make the axes stay consistent when the timeline changes).

backgroundConfigrecordDefault {duration: 0, fill: transparent}

A d3plus-shape configuration Object used for styling the background rectangle of the inner x/y plot (behind all of the shapes and gridlines).

baselinenumber

Starts the value axis (the x axis for horizontal charts) at a value: baseline(n) renders exactly like yDomain([n]) (or xDomain([n])). Bars, areas, and stems still grow from the chart's own 0 in the Plots that draw from one (such as BarChart, AreaPlot, Histogram, and Lollipop), so with baselineBreak on (their default) the axis breaks back to a 0 tick and bars run through the break, with its gap cut across them, and with it off the axis stretches down to 0. As with yDomain([n]), only n is pinned: the far end comes from the data and is rounded where the axis would round it with no domain set (left at the data when the axis config's rounding is "none"), and marks for values past n stop at the axis's edge. When every value sits at or below n, it ends the axis instead, like yDomain([undefined, n]). A bound given in yDomain/xDomain wins. Returns the chart's own baseline when none is set.

bufferboolean | recordDefault assign({}, defaultBuffers, {Bar: false, Line: false})

Determines whether or not to add additional padding at the ends of x or y scales. The most commone use for this is in Scatter Plots, so that the shapes do not appear directly on the axis itself. The value provided can either be true or false to toggle the behavior for all shape types, or a keyed Object for each shape type (ie. {Bar: false, Circle: true, Line: false}).

classNamestring | array.<string> | undefined

CSS classes added to the outermost element this chart or component draws into, next to its fixed d3plus classes, so page CSS can target it: a chart's root <svg class="d3plus-viz"> (its <canvas> with the Canvas renderer) and a standalone component's <svg>. Takes a space-separated string or an array. A new value replaces the classes the previous one added; unset adds none. Tooltips take their own tooltipConfig.className.

colorDefaultscolordefaultsconfig

Overrides the default colors used when assigning fills from data and choosing legible text colors: dark and light (the text colors picked for contrast against a background), missing (null/undefined values), on/off (true/false values), sequential (the anchor hue for magnitude ramps), and scale (the categorical palette, given as a d3 ordinal scale or an array of colors). Keys are merged into the current defaults, and a Viz passes its overrides down to the shapes and components it draws.

configd3plusconfig

Methods that correspond to the key/value pairs and returns this class.

crosshairConfigrecordDefault
function
{stroke: () => themed(this._theme, (t) => t.textMuted, colorGray.500), strokeDasharray: 4 3, strokeWidth: 1}

Paint for the shared tooltip's crosshair guide line (stroke, strokeWidth, strokeDasharray, strokeOpacity, …). Merged into the current config.

datastring | array.&lt;datapoint&gt; | object

The primary data array used to draw the visualization. The value passed should be an Array of objects or a String representing a filepath or URL to be loaded. The following filetypes are supported: csv, tsv, txt, and json.

If your data URL needs specific headers to be set, an Object with a "url" and "headers" (or any other fetch request option) may also be passed. An Object with any other key is a data row, not a request.

Additionally, a custom formatting function can be passed as a second argument to this method. This custom function will be passed the data that has been loaded, as long as there are no errors. This function should return the final array of obejcts to be used as the primary data array. For example, some JSON APIs return the headers split from the data values to save bandwidth. These would need be joined using a custom formatter.

If you would like to specify certain configuration options based on the yet-to-be-loaded data, you can also return a full config object from the data formatter (including the new data array as a key in the object).

To re-fetch a URL on an interval and redraw when its data changes, set dataPollingInterval; each poll runs the same formatter.

Defaults to an empty array ([]).

facetstring | false | function

Splits the chart into small multiples: a grid of equally sized panels, one per distinct value of this data key or accessor, each drawing the chart for that value's rows. The panels share one legend, color scale, title, and timeline, color each series the same way, and hover, tooltips, and legend clicks apply across all of them. Pass false to draw a single chart. See facetConfig for the grid's layout and shared scales.

facetConfigfacetconfig

Configuration for small multiples (see facet), merged into the current config: - columns / rows: the grid's shape. Chosen by default to make the panels as large as the chart's shape allows. - padding: the space between panels, in pixels (default 20). - sort: panel order — "ascending" (default), "descending", "data" (first appearance), a comparator over facet values, or an Array of values. - scales: "shared" (default) gives every panel of a chart with axes the same x/y domains; "independent" fits each panel to its own rows. Funnel defaults to "independent" (each panel sized to its own widest stage); "shared" sizes every panel against the widest stage across all panels. PolarArea and RadialBar default to "independent" (each panel's rings and ticks fit its own values); "shared" gives every panel the same value domain. - axes: with shared scales, "outer" (default) labels the axes only along the grid's left and bottom edges; "all" labels every panel. An object sets each axis on its own, as in {x: "all", y: "outer"}: every panel labels its x axis, only the left column labels its y axis, and the panels' plot areas line up. BumpChart defaults to "all", and Marimekko labels its categories on every panel and its 0–100% share axis only along the outer edge, even with independent scales. - title: a (value, data) => string function for each panel's title, or false to hide panel titles. - titleConfig: TextBox config for the panel titles (fontSize, fontWeight, fontColor, textAnchor, padding, …).

fontFamilystring | array.&lt;string&gt;

The font family used throughout the visualization.

groupBystring | function | array.&lt;string | function&gt;

Defines the mapping between data and shape. The value can be a String matching a key in each data point (default is "id"), or an accessor Function that returns a unique value for each data point. Additionally, an Array of these values may be provided if the visualization supports nested hierarchies.

highlightfalse | function

Persistently emphasizes the data points matching the given predicate: the matching marks keep their color while every other mark is de-emphasized to a neutral gray (the "emphasis" form — highlight one series, gray the rest). Unlike hover/active (transient, opacity-based), highlight is a standing state that survives pointer movement. Pass false to clear it.

hoverfalse | function

The hover callback function for highlighting shapes on mouseover.

localestring | object

The locale used for all text and number formatting. Supports the locales defined in d3plus-format. The locale can be a complex Object, a locale code (like "en-US"), or a 2-digit language code (like "en"). If a 2-digit code is provided, the "findLocale" function is used to identify the most approximate locale.

onstring

Event listener for the specified event typenames. Mirrors the core d3-selection behavior.

parentunknown

Parent config used by the wrapper.

renderfunction

Draws the visualization given the specified configuration.

rendererboolean | "svg" | "canvas"

Selects which @d3plus/render backend paints the visible output. "svg" = SvgRenderer (default), "canvas" = CanvasRenderer. Boolean arguments both normalize to "svg".

selectstring | htmlelement

The SVG container element as a d3 selector or DOM element. Defaults to undefined.

shapeConfigd3plusconfigDefault {Circle: {label: false, trail: false}}

Configuration object with key/value pairs applied as method calls on each shape.

sizefalse | plotaccessorarg

Sets the size of bubbles to the given Number, data key, or function.

swarmboolean | "x" | "y"Default true

Beeswarm swarms by default (true): along x when its values are numeric, else along y.

thresholdnumber | function

The threshold value for bucketing small data points together, as a share of the total. On a stacked Plot, the series whose summed value across every position is under that share of the whole chart's total merge into one series, stacked on top. A bucket needs at least two items, and its tooltips list them. Off (0) by default on Plot charts.

thresholdKeystring | function

Accessor for the value used in the threshold algorithm. A stacked Plot defaults to its stacked value.

timestring | false | function

Accessor function or string key for the time dimension of each data point.

timelineDefaultstring | date | array.&lt;string | date&gt;

The starting time or range for the timeline. Can be a single Date/String, or an Array of 2 values representing the min and max.

totalstring | boolean | function

Accessor function or string key for the total value displayed in the visualization.

translatefunction

Defines how informational text strings should be displayed. By default, this function will try to find the string in question (which is the first argument provided to this function) inside of an internally managed translation Object. If you'd like to override to use custom text, simply pass this method your own custom formatting function.

trendLinetrendlinetype

Draws an automatic trend line fit to the plotted data: true (or "linear") for a least-squares line, or one of "exponential", "logarithmic", "power", or "polynomial". By default each series gets its own line in its color; see trendLineConfig for grouping, a confidence band, and styling. On a chart with a discrete axis, the line runs along that axis, fitting categories by their order. Set to false (the default) to remove.

trendLineConfigrecord

Options for the trend lines drawn by trendLine, merged into the current config: - group: "series" (default) fits one line per series, colored to match it; "all" fits a single line to every point. - order: the polynomial degree when trendLine is "polynomial" (default 2). - confidence: draws a confidence band around a linear fit (default false). - confidenceLevel: the band's confidence level (default 0.95). - confidenceConfig: Area shape config for the band (default {fillOpacity: 0.15}; fill defaults to the line color). - projection: extends each line past the end of its data, by a number of steps at the data's own spacing (e.g. 5 more years), or to an end value with {to: 2030} (default 0, off). The axis widens to fit, and a linear fit's band becomes a prediction interval that fans out over the projection. Hovering a projected step lists each series' projected value. Ignored on a category axis. - projectionConfig: Line shape config for the projected stretch, over the line's own styles (default {strokeDasharray: "2 4"}). - tooltip: shows the fitted equation and R² when hovering a line (default true). - Any other key (stroke, strokeWidth, strokeDasharray, …) styles the Line shape.

Stacked charts always fit one line to the stack totals.

xplotaccessorargDefault
function
d => d["x"]

Accessor function or string key for the x-axis value of each data point.

x2plotaccessorargDefault
function
d => d["x2"]

Accessor function or string key for the secondary x-axis value of each data point.

x2ConfigrecordDefault {}

A pass-through to the underlying Axis config used for the secondary x-axis. Includes additional functionality where passing "auto" as the value for the scale method will determine if the scale should be "linear" or "log" based on the provided data.

xConfigrecordDefault
function
{gridConfig: {stroke: (d) => {
  if (this.schema.discrete?.charAt(0) === "x" || this._swarm?.cross === "x") return "transparent";
  const range = this._xAxis.range();
  const position = this._xAxis._getPosition.bind(this._xAxis)(d.id);
  if (range[0] === position) return "transparent";
  return chartGridline(this);
}}}

A pass-through to the underlying Axis config used for the x-axis. Includes additional functionality where passing "auto" as the value for the scale method will determine if the scale should be "linear" or "log" based on the provided data.

yplotaccessorargDefault
function
d => d["y"]

Accessor function or string key for the y-axis value of each data point.

y2plotaccessorargDefault
function
d => d["y2"]

Accessor function or string key for the secondary y-axis value of each data point.

y2ConfigrecordDefault {}

A pass-through to the underlying Axis config used for the secondary y-axis. Includes additional functionality where passing "auto" as the value for the scale method will determine if the scale should be "linear" or "log" based on the provided data.

yConfigrecordDefault
function
{gridConfig: {stroke: (d) => {
  if (this.schema.discrete?.charAt(0) === "y" || this._swarm?.cross === "y") return "transparent";
  const range = this._yAxis.range();
  const position = this._yAxis._getPosition.bind(this._yAxis)(d.id);
  if (range[range.length - 1] === position) return "transparent";
  return chartGridline(this);
}}}

A pass-through to the underlying Axis config used for the y-axis. Includes additional functionality where passing "auto" as the value for the scale method will determine if the scale should be "linear" or "log" based on the provided data.

Note: If a "domain" array is passed to the y-axis config, it will be reversed.