Skip to content

BarChart

Creates a bar chart based on an array of data. When stacked, each bar’s fraction of its stack total is available to tooltip accessors as share (unless the data has its own share field).

A minimal grouped bar chart: the two series in groupBy share each x position and sit side by side, with each bar’s height read from y.

const config = {
  data: [
    {id: "alpha", x: 4, y: 7},
    {id: "alpha", x: 5, y: 25},
    {id: "alpha", x: 6, y: 13},
    {id: "beta", x: 4, y: 17},
    {id: "beta", x: 5, y: 8},
    {id: "beta", x: 6, y: 13},
  ],
  groupBy: "id",
  x: "x",
  y: "y",
};

The discrete x axis sorts alphabetically by default; pass an xSort comparator to order the bars by a different field — here the travel-time buckets follow their numeric "ID Travel Time" instead of their labels.

const config = {
  data: [
    {
      "Travel Time": "< 5 Minutes",
      "ID Travel Time": "0",
      "Population Percentage": 2,
    },
    {
      "Travel Time": "15 - 24 Minutes",
      "ID Travel Time": "2",
      "Population Percentage": 30,
    },
    {
      "Travel Time": "35 - 44 Minutes",
      "ID Travel Time": "4",
      "Population Percentage": 7,
    },
    {
      "Travel Time": "45 - 89 Minutes",
      "ID Travel Time": "5",
      "Population Percentage": 11,
    },
    {
      "Travel Time": "5 - 14 Minutes",
      "ID Travel Time": "1",
      "Population Percentage": 20,
    },
    {
      "Travel Time": "90+ Minutes",
      "ID Travel Time": "6",
      "Population Percentage": 5,
    },
    {
      "Travel Time": "25 - 34 Minutes",
      "ID Travel Time": "3",
      "Population Percentage": 25,
    },
  ],
  groupBy: "Travel Time",
  x: "Travel Time",
  y: "Population Percentage",
  xSort: (a, b) => a["ID Travel Time"] - b["ID Travel Time"],
};

barPadding sets the pixel gap between bars within a group, while groupPadding sets the gap between adjacent groups — raise the latter to visually separate each x cluster.

The pixel space between groups of bars.

Set stacked: true to stack the series into one bar per x position rather than grouping them side by side, emphasizing the combined total over per-series comparison.

The pixel space between groups of bars.

discrete

Sets orientation of main category axis.

Run the bars horizontally by setting discrete: "y" so the category sits on the vertical axis and the measured length extends along x. Reach for this when category labels are long or numerous.

discrete

Sets orientation of main category axis.

Any axis config takes reverse: true to flip that axis. A horizontal bar chart’s categories run up from the bottom, so the latest year would sit on top; reversing the y axis reads the years down from the earliest, like a table. The bars, labels, and tooltips all follow the reversed axis.

const config = {
  data: ["Coal", "Gas", "Solar"].flatMap((source, k) =>
    [2018, 2019, 2020, 2021, 2022, 2023].map((year, i) => ({
      source,
      year,
      value: 10 + k * 5 + i * (k + 1),
    })),
  ),
  discrete: "y",
  groupBy: "source",
  stacked: true,
  x: "value",
  y: "year",
  yConfig: {reverse: true},
};

trendLine works on the discrete axis too: each series gets a line fit across its bars, sampled at every category and drawn behind them. Categories that aren’t numbers or dates are fit by their order along the axis.

const config = {
  data: [
    {id: "alpha", year: 2019, value: 42},
    {id: "alpha", year: 2020, value: 38},
    {id: "alpha", year: 2021, value: 51},
    {id: "alpha", year: 2022, value: 57},
    {id: "alpha", year: 2023, value: 55},
    {id: "alpha", year: 2024, value: 66},
    {id: "beta", year: 2019, value: 61},
    {id: "beta", year: 2020, value: 63},
    {id: "beta", year: 2021, value: 56},
    {id: "beta", year: 2022, value: 54},
    {id: "beta", year: 2023, value: 49},
    {id: "beta", year: 2024, value: 47},
  ],
  groupBy: "id",
  x: "year",
  y: "value",
  trendLine: true,
  trendLineConfig: {strokeWidth: 3},
};

On a numeric or time axis, trendLineConfig.projection adds future slots to the axis and carries each series’ trend line across them. Categories that aren’t numbers or dates have no next value, so they ignore it. The projected slots are marked as a forecast, shaded from the edge of the first one; set forecast: false to leave them unmarked.

const config = {
  data: [
    {id: "alpha", year: 2019, value: 42},
    {id: "alpha", year: 2020, value: 38},
    {id: "alpha", year: 2021, value: 51},
    {id: "alpha", year: 2022, value: 57},
    {id: "alpha", year: 2023, value: 55},
    {id: "alpha", year: 2024, value: 66},
    {id: "beta", year: 2019, value: 61},
    {id: "beta", year: 2020, value: 63},
    {id: "beta", year: 2021, value: 56},
    {id: "beta", year: 2022, value: 54},
    {id: "beta", year: 2023, value: 49},
    {id: "beta", year: 2024, value: 47},
  ],
  groupBy: "id",
  x: "year",
  y: "value",
  trendLine: true,
  trendLineConfig: {projection: 3},
};

Overlay a repeating pattern on the bars via shapeConfig.texture (here "nylon"), with textureDefault tuning its size and stroke — useful for keeping series distinguishable in print or grayscale.

const config = {
  data: [
    {id: "alpha", x: 4, y: 7},
    {id: "alpha", x: 5, y: 25},
    {id: "alpha", x: 6, y: 13},
    {id: "beta", x: 4, y: 17},
    {id: "beta", x: 5, y: 8},
    {id: "beta", x: 6, y: 13},
  ],
  groupBy: "id",
  shapeConfig: {
    texture: "nylon",
    textureDefault: {
      size: 10,
      stroke: "rgba(0, 0, 0, 0.1)",
      strokeWidth: 1,
    },
  },
  x: "x",
  y: "y",
};

A population pyramid: age ranges run up the discrete y axis while the x accessor negates the female Population so the sexes mirror around zero, and xConfig.tickFormat restores absolute labels. Use it to read a population’s age-and-sex structure at a glance.

const config = {
  groupPadding: 2,
  data: [
    {
      "Age range": "0 to 4",
      Sex: "Male",
      Population: 1445122,
    },
    {
      "Age range": "0 to 4",
      Sex: "Female",
      Population: 1385933,
    },
    {
      "Age range": "5 to 9",
      Sex: "Male",
      Population: 1473968,
    },
    {
      "Age range": "5 to 9",
      Sex: "Female",
      Population: 1417319,
    },
    {
      "Age range": "10 to 15",
      Sex: "Male",
      Population: 1483727,
    },
    {
      "Age range": "10 to 15",
      Sex: "Female",
      Population: 1430083,
    },
    {
      "Age range": "15 to 19",
      Sex: "Male",
      Population: 1466289,
    },
    {
      "Age range": "15 to 19",
      Sex: "Female",
      Population: 1420257,
    },
    {
      "Age range": "20 to 24",
      Sex: "Male",
      Population: 1438000,
    },
    {
      "Age range": "20 to 24",
      Sex: "Female",
      Population: 1401017,
    },
    {
      "Age range": "25 to 29",
      Sex: "Male",
      Population: 1371191,
    },
    {
      "Age range": "25 to 29",
      Sex: "Female",
      Population: 1344048,
    },
    {
      "Age range": "30 to 34",
      Sex: "Male",
      Population: 1251238,
    },
    {
      "Age range": "30 to 34",
      Sex: "Female",
      Population: 1233884,
    },
    {
      "Age range": "35 to 39",
      Sex: "Male",
      Population: 1156915,
    },
    {
      "Age range": "35 to 39",
      Sex: "Female",
      Population: 1145477,
    },
    {
      "Age range": "40 to 44",
      Sex: "Male",
      Population: 1038422,
    },
    {
      "Age range": "40 to 44",
      Sex: "Female",
      Population: 1034343,
    },
    {
      "Age range": "45 to 49",
      Sex: "Male",
      Population: 899326,
    },
    {
      "Age range": "45 to 49",
      Sex: "Female",
      Population: 903752,
    },
    {
      "Age range": "50 to 54",
      Sex: "Male",
      Population: 774590,
    },
    {
      "Age range": "50 to 54",
      Sex: "Female",
      Population: 788241,
    },
    {
      "Age range": "55 to 59",
      Sex: "Male",
      Population: 634510,
    },
    {
      "Age range": "55 to 59",
      Sex: "Female",
      Population: 658490,
    },
    {
      "Age range": "60 to 64",
      Sex: "Male",
      Population: 501128,
    },
    {
      "Age range": "60 to 64",
      Sex: "Female",
      Population: 532940,
    },
    {
      "Age range": "65 to 69",
      Sex: "Male",
      Population: 379352,
    },
    {
      "Age range": "65 to 69",
      Sex: "Female",
      Population: 415647,
    },
    {
      "Age range": "70 to 74",
      Sex: "Male",
      Population: 271687,
    },
    {
      "Age range": "70 to 74",
      Sex: "Female",
      Population: 311231,
    },
    {
      "Age range": "75 to 79",
      Sex: "Male",
      Population: 186805,
    },
    {
      "Age range": "75 to 79",
      Sex: "Female",
      Population: 229221,
    },
    {
      "Age range": "80+",
      Sex: "Male",
      Population: 166789,
    },
    {
      "Age range": "80+",
      Sex: "Female",
      Population: 235076,
    },
  ],
  discrete: "y",
  groupBy: "Sex",
  shapeConfig: {
    label: d => d["Age range"],
  },
  stacked: true,
  x: d => d.Population * (d.Sex === "Female" ? -1 : 1),
  xConfig: {
    tickFormat: d => formatAbbreviate(Math.abs(d)),
  },
  y: "Age range",
  yConfig: {barConfig: {stroke: "transparent"}, ticks: []},
};

Set renderer: "canvas" to paint to a <canvas> element instead of SVG. Useful for charts with very large numbers of shapes; hover, tooltips, and pointer events still work. SVG is the default.

renderer

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

Register pointer handlers via on. Open the browser console, then click or hover a bar. Event names mirror d3-selection; the .shape namespace scopes the handler to data marks (use .legend for legend entries, or a shape class like .Bar). The handler receives the datum.

on

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

{}

Replace the default hover card with tooltipConfig: title builds the header from the datum and tbody lists label/value rows. Hover a bar to see the custom formatting.

const featureData = [
  {region: "North", quarter: "Q1", revenue: 35},
  {region: "North", quarter: "Q2", revenue: 50},
  {region: "North", quarter: "Q3", revenue: 42},
  {region: "North", quarter: "Q4", revenue: 47},
  {region: "South", quarter: "Q1", revenue: 20},
  {region: "South", quarter: "Q2", revenue: 30},
  {region: "South", quarter: "Q3", revenue: 38},
  {region: "South", quarter: "Q4", revenue: 33},
];

const config = {
  data: featureData,
  groupBy: "region",
  x: "quarter",
  y: "revenue",
  tooltipConfig: {
    title: d => `${d.region} — ${d.quarter}`,
    tbody: [
      ["Region", d => d.region],
      ["Revenue", d => `$${d.revenue}M`],
    ],
  },
};

Pass a locale (here "ar-SA") to translate built-in UI text and format numbers for that region. Right-to-left locales also flip layout. Dictionaries live in @d3plus/locales.

const featureData = [
  {region: "North", quarter: "Q1", revenue: 35},
  {region: "North", quarter: "Q2", revenue: 50},
  {region: "North", quarter: "Q3", revenue: 42},
  {region: "North", quarter: "Q4", revenue: 47},
  {region: "South", quarter: "Q1", revenue: 20},
  {region: "South", quarter: "Q2", revenue: 30},
  {region: "South", quarter: "Q3", revenue: 38},
  {region: "South", quarter: "Q4", revenue: 33},
];

const config = {
  data: featureData.map(d => ({...d, revenue: d.revenue * 1000000})),
  groupBy: "region",
  x: "quarter",
  y: "revenue",
  locale: "ar-SA",
};

highlight keeps the matching marks in color and de-emphasizes the rest to a neutral gray — the “emphasis” pattern for pointing at one series without hiding the others. Unlike hover/active (transient, opacity-based) it is a standing state, so it persists until cleared with false.

const featureData = [
  {region: "North", quarter: "Q1", revenue: 35},
  {region: "North", quarter: "Q2", revenue: 50},
  {region: "North", quarter: "Q3", revenue: 42},
  {region: "North", quarter: "Q4", revenue: 47},
  {region: "South", quarter: "Q1", revenue: 20},
  {region: "South", quarter: "Q2", revenue: 30},
  {region: "South", quarter: "Q3", revenue: 38},
  {region: "South", quarter: "Q4", revenue: 33},
];

const config = {
  data: featureData,
  groupBy: "region",
  x: "quarter",
  y: "revenue",
  highlight: d => d.region === "North",
};

Set colorOrdinal: true to color an ordered discrete field with a single-hue light→dark ramp instead of unrelated categorical hues, so the color itself carries the order. The ramp follows the data order (numeric values sort ascending); here the tiers run XS→XL from light to dark.

const tierData = [
  {tier: "XS", sales: 12},
  {tier: "S", sales: 28},
  {tier: "M", sales: 45},
  {tier: "L", sales: 33},
  {tier: "XL", sales: 19},
];

const config = {
  data: tierData,
  groupBy: "tier",
  x: "tier",
  y: "sales",
  color: "tier",
  colorOrdinal: true,
  xSort: (a, b) =>
    ["XS", "S", "M", "L", "XL"].indexOf(a.tier) -
    ["XS", "S", "M", "L", "XL"].indexOf(b.tier),
};

stackOrder accepts named value orders that rank series by their summed total. "descending" (the default) anchors the largest series — Enterprise — on the baseline with the smallest on top; switch to "ascending" to flip that and put the largest on top. Unlike the old alphabetical default, this reads by magnitude and works the same whether x is a string or a number (see #527).

const revenueByYear = [
  {segment: "Enterprise", year: 2021, revenue: 40},
  {segment: "Enterprise", year: 2022, revenue: 46},
  {segment: "Enterprise", year: 2023, revenue: 52},
  {segment: "Retail", year: 2021, revenue: 25},
  {segment: "Retail", year: 2022, revenue: 28},
  {segment: "Retail", year: 2023, revenue: 27},
  {segment: "Online", year: 2021, revenue: 8},
  {segment: "Online", year: 2022, revenue: 14},
  {segment: "Online", year: 2023, revenue: 21},
];

const config = {
  data: revenueByYear,
  groupBy: "segment",
  stacked: true,
  stackOrder: "descending",
  x: "year",
  y: "revenue",
};

Pass an accessor (or a {value, order} config) to order the stack by any field, not just the plotted one. Here bar height is units, but the stack is ordered by total profit — so low-volume, high-profit Gadgets sinks to the baseline while the tall Widgets band rides on top. Series are ranked by the summed accessor value, descending by default; use {value: "profit", order: "ascending"} to reverse.

const config = {
  data: [
    {product: "Widgets", quarter: "Q1", units: 50, profit: 5},
    {product: "Widgets", quarter: "Q2", units: 60, profit: 6},
    {product: "Gadgets", quarter: "Q1", units: 20, profit: 40},
    {product: "Gadgets", quarter: "Q2", units: 25, profit: 50},
    {product: "Gizmos", quarter: "Q1", units: 35, profit: 15},
    {product: "Gizmos", quarter: "Q2", units: 30, profit: 18},
  ],
  groupBy: "product",
  stacked: true,
  stackOrder: d => d.profit,
  x: "quarter",
  y: "units",
};

When a yDomain (or yConfig.domain) stops short of zero, the axis still ends at a 0 tick, then breaks — two short tilted marks with a gap in the axis line — and resumes at the domain’s minimum. Bars start at the 0 tick, so they never spill past the axis, and the break’s gap is cut straight across them, as with a yBreak. Turn baselineBreak off and a yDomain stretches back down to 0 (a yConfig.domain is kept, with the bars cut off at the axis); style the break with yConfig.baselineBreakConfig (space, gap, size, angle, stroke, and mask: false to leave the bars whole). See #645.

When the domain of a linear value axis stops short of the baseline (e.g. [1100, 2100] with a baseline of 0), keeps the baseline as the axis's end tick and breaks the axis between it and the domain: a short stretch of axis holds the baseline tick and two tilted marks with a gap in the axis line, then the domain spans the rest. Style it with the axis's baselineBreakConfig. In a Plot it applies to a user-supplied value domain (yDomain/yConfig.domain, or the x versions for horizontal charts), and bars and areas start at the baseline tick, with the break's gap cut across them (baselineBreakConfig's mask); turned off, a yDomain stretches to reach the baseline while a yConfig.domain is kept and cuts its bars off at the axis. Defaults to true for the Plots whose marks grow from 0, such as BarChart, AreaPlot, Histogram, and Lollipop (each chart lists its own default), and false for other Plots and a standalone Axis.

Horizontal bars break their x axis the same way, here with a steeper, wider break glyph set through xConfig.baselineBreakConfig.

const housingStarts = [
  {year: 2019, starts: 1290},
  {year: 2020, starts: 1380},
  {year: 2021, starts: 1601},
  {year: 2022, starts: 1553},
  {year: 2023, starts: 1420},
  {year: 2024, starts: 1367},
];

const config = {
  data: housingStarts,
  discrete: "y",
  groupBy: "year",
  x: "starts",
  xConfig: {
    baselineBreakConfig: {angle: 45, gap: 6, size: 14},
    domain: [1200, 1700],
  },
  y: "year",
};

baseline(1200) renders exactly like yDomain([1200]): the y axis starts at exactly 1200 (its top is still rounded, just as it is with no domain set), then breaks back to a 0 tick, and the bars still grow from that 0 through the break, which cuts its gap across them. Turn baselineBreak off and the axis stretches down to 0, just as a yDomain minimum does. A yDomain bound wins over the baseline, and when every value sits below the baseline it ends the axis instead, like yDomain([undefined, n]).

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.

When the domain of a linear value axis stops short of the baseline (e.g. [1100, 2100] with a baseline of 0), keeps the baseline as the axis's end tick and breaks the axis between it and the domain: a short stretch of axis holds the baseline tick and two tilted marks with a gap in the axis line, then the domain spans the rest. Style it with the axis's baselineBreakConfig. In a Plot it applies to a user-supplied value domain (yDomain/yConfig.domain, or the x versions for horizontal charts), and bars and areas start at the baseline tick, with the break's gap cut across them (baselineBreakConfig's mask); turned off, a yDomain stretches to reach the baseline while a yConfig.domain is kept and cuts its bars off at the axis. Defaults to true for the Plots whose marks grow from 0, such as BarChart, AreaPlot, Histogram, and Lollipop (each chart lists its own default), and false for other Plots and a standalone Axis.

One outlier would flatten every other bar. yBreak removes a value range from the y axis — here 80 to 900 — so the small bars keep a readable scale while the outlier still reaches its real value. The axis shows the break with two short marks and labels both of its edges; a line runs across the plot from each mark, and the gap between the two lines is cut straight across the bar that crosses it. Pass a list of ranges ([[80, 400], [500, 900]]) for several breaks, and style them with yConfig.breakConfig (lineConfig styles the lines, lines: false hides them, and mask: false leaves the shapes whole). See #766 and #767.

const config = {
  data: [
    {region: "North", sales: 42},
    {region: "South", sales: 58},
    {region: "East", sales: 35},
    {region: "Online", sales: 960},
    {region: "West", sales: 51},
  ],
  groupBy: "region",
  x: "region",
  y: "sales",
  yBreak: [80, 900],
};

Supply confidence as a [lower, upper] pair of data keys (or accessors) to draw an error bar on every bar: a line from the lower to the upper bound, capped at each end and centered on its bar. The value axis widens to fit the bounds, and a bar’s tooltip (hover its bar or its error bar) lists its Lower and Upper Bound; set confidenceConfig.tooltip to false to leave them out, or confidence to false to turn the interval off.

const surveyResults = [
  {region: "North", year: "2023", pct: 42, lower: 38.5, upper: 45.6},
  {region: "North", year: "2024", pct: 47, lower: 43.2, upper: 50.9},
  {region: "South", year: "2023", pct: 35, lower: 30.1, upper: 39.8},
  {region: "South", year: "2024", pct: 31, lower: 27.4, upper: 34.7},
  {region: "West", year: "2023", pct: 51, lower: 45.0, upper: 56.8},
  {region: "West", year: "2024", pct: 55, lower: 50.3, upper: 59.6},
];

const config = {
  data: surveyResults,
  groupBy: "year",
  confidence: ["lower", "upper"],
  x: "region",
  y: "pct",
};

Error bars follow the bars’ orientation. confidenceConfig styles them: stroke and strokeWidth paint the line (by default a shade darker than its bar, 2px wide), and capWidth sets the end caps’ length, in pixels or as a percentage of the bar’s thickness (default "50%").

discrete

Sets orientation of main category axis.

On stacked bars, each segment’s error bar sits at the segment’s stacked end, keeping its bounds’ distance from the segment’s own value — so it shows that segment’s uncertainty, not the stack total’s. The shared tooltip lists each segment’s own bounds after its value.

const surveyResults = [
  {region: "North", year: "2023", pct: 42, lower: 38.5, upper: 45.6},
  {region: "North", year: "2024", pct: 47, lower: 43.2, upper: 50.9},
  {region: "South", year: "2023", pct: 35, lower: 30.1, upper: 39.8},
  {region: "South", year: "2024", pct: 31, lower: 27.4, upper: 34.7},
  {region: "West", year: "2023", pct: 51, lower: 45.0, upper: 56.8},
  {region: "West", year: "2024", pct: 55, lower: 50.3, upper: 59.6},
];

const config = {
  data: surveyResults,
  groupBy: "year",
  confidence: [d => d.lower, d => d.upper],
  stacked: true,
  x: "region",
  y: "pct",
};

Bars named by their own groupBy category carry that name inside the bar, and the category axis leaves its tick labels off. When the bars are too narrow for their names, as these 36 months are, the axis labels the categories instead (rotating or thinning them as any crowded axis does) and the bars drop theirs, so every bar stays named.

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.

Side-by-side bars answer the pointer anywhere in their slot, from one edge of the plot to the other, so East’s tiny bar shows its tooltip and takes clicks when you hover high above it. Grouped bars each own their column of the slot; stacked bars already fill theirs. shapeConfig: {Bar: {hitArea: false}} limits hovering to the bars themselves.

const config = {
  data: [
    {region: "North", sales: 42},
    {region: "South", sales: 58},
    {region: "East", sales: 0.6},
    {region: "West", sales: 51},
    {region: "Online", sales: 64},
  ],
  groupBy: "region",
  x: "region",
  y: "sales",
};

An axis config’s labelRotation takes a number of degrees as well as true (-90) or false. At -45 each long category name rises to the right and ends at its bar’s tick; a positive angle falls to the right from its tick instead. The axis claims the room the slanted labels need, and thins them when their text would touch.

const config = {
  data: [
    {id: "Agriculture, Forestry and Fishing", value: 20},
    {id: "Mining and Quarrying", value: 57},
    {id: "Manufacturing", value: 94},
    {id: "Electricity and Gas Supply", value: 41},
    {id: "Water Supply and Sewerage", value: 78},
    {id: "Construction", value: 25},
    {id: "Wholesale and Retail Trade", value: 62},
    {id: "Transportation and Storage", value: 99},
  ],
  groupBy: "id",
  legend: false,
  shapeConfig: {Bar: {label: false}},
  x: "id",
  xConfig: {labelRotation: -45},
  y: "value",
};

Configuration

import {BarChart} 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).

barWidthstring | false | function

Makes each bar as wide as its own measure (a data key or accessor), read off the merge of the bar's rows, so stacked segments add up unless aggs says otherwise. The bars sit end to end along a continuous discrete axis of cumulative width, labeled at their centers. Off (undefined) by default.

barWidthShareboolean | "opposite"Default false

With barWidth, adds each bar's share of the total width to its category's axis label: on a second line beneath the name along a horizontal axis, in parentheses after it along a vertical one. Along a horizontal axis, a name wraps to fit a narrow bar, widening into room its neighbors leave; a label that still can't fit is left out, and the labels rotate, showing the name alone, only when half or more can't fit. "opposite" puts the shares on the axis across the bars from the names instead: above them along a horizontal axis (x2Config), right of them along a vertical one (y2Config). In small multiples, each panel's shares are of that panel's own total width. Off (false) by default.

barWidthShareFormatfunction

With barWidthShare, returns each bar's width-share label in place of its percentage. Called with the merge of the bar's rows' data and {share, size, total, text}: the bar's share of the total width (0–1), its width measure, every bar's combined width, and the default label (such as "23%"). Unset by default.

baselinenumberDefault 0

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.

baselineBreakbooleanDefault true

When the domain of a linear value axis stops short of the baseline (e.g. [1100, 2100] with a baseline of 0), keeps the baseline as the axis's end tick and breaks the axis between it and the domain: a short stretch of axis holds the baseline tick and two tilted marks with a gap in the axis line, then the domain spans the rest. Style it with the axis's baselineBreakConfig. In a Plot it applies to a user-supplied value domain (yDomain/yConfig.domain, or the x versions for horizontal charts), and bars and areas start at the baseline tick, with the break's gap cut across them (baselineBreakConfig's mask); turned off, a yDomain stretches to reach the baseline while a yConfig.domain is kept and cuts its bars off at the axis. Defaults to true for the Plots whose marks grow from 0, such as BarChart, AreaPlot, Histogram, and Lollipop (each chart lists its own default), and false for other Plots and a standalone Axis.

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.&lt;string&gt; | 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.

confidenceunknown

The confidence interval as an array of [lower, upper] bounds. Lines draw it as a shaded band; bars draw an error bar per bar, from the lower to the upper bound with a cap at each end (a stacked bar's bounds keep their distance from its value, measured from the bar's stacked end). Either bound may be false for a one-sided interval, and a row without a bound pinches the band onto its line. The value axis widens to fit the bounds, and tooltips list them (see confidenceConfig.tooltip). Pass false to turn the interval off.

Pass an array of bands, outermost first, to draw nested bands around each line (a fan): each band is a [lower, upper] pair or [lower, upper, label], or a {lower, upper, label} object, and confidenceConfig.bandOpacity shades them from the widest (lightest) to the narrowest (darkest). Tooltips list each band's range under its label ("Band 1", "Band 2", … when unlabeled), and bars draw the first band's error bar.

confidenceConfigrecordDefault
function
{fill: (d, i) => {
  const { Line, stroke } = this.schema.shapeConfig;
  const s = Line && Line.stroke !== undefined ? Line.stroke : stroke;
  return typeof s === "function" ? s(d, i) : s;
}, fillOpacity: 0.5}

Configuration object for shapes rendered as confidence intervals. A line's band is an Area, filled with the line's color at half opacity. A bar's error bar is a Path styled by stroke (default a shade darker than the bar), strokeWidth (default 2), strokeDasharray, strokeOpacity, and capWidth: the length of each end cap, in pixels or as a percentage string of the bar's thickness (default "50%"). Keys nested under Area or Bar apply only to that shape's interval. With several bands, bandOpacity sets how each band looks where it is the innermost band drawn: an array ramps from the outermost band to the innermost (default [0.15, 0.6]), a number gives every band that opacity, and either replaces fillOpacity. tooltip (default true) lists the bounds in tooltips: a "Lower Bound" and "Upper Bound" row for a single mark, and a range after each series' value in a shared tooltip; set it to false to leave them out. Accepted keys: any key the Area or Path shape takes at the top level, plus bandOpacity, capWidth, tooltip, Area (Area keys), and Bar (Path keys and capWidth); any other key logs a warning.

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 ([]).

discrete"x" | "y" | "radius" | "angle"Default "x"

Sets orientation of main category axis.

discreteCutoffnumberDefault unknown

When the width or height of the chart is less than or equal to this pixel value, the discrete axis will not be shown. This helps produce slick sparklines. Set this value to 0 to disable the behavior entirely.

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.

groupPaddingnumberDefault unknown

The pixel space between groups of bars.

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.

labelConnectorConfigrecordDefault {strokeDasharray: 1 1}

The d3plus-shape config used on the Line shapes created to connect lineLabels to the end of their associated Line path.

legendboolean | functionDefault function

Whether to display the legend. By default, the legend shows when it has more than one entry and each entry stands for a single group (or two groups at most), or when the entries are colored by a category that isn't a groupBy level (see color), in which case each entry is labelled by its category. Pass false to hide it, true to always show it, or a (config, data) => boolean function to decide.

lineMarkerConfigrecordDefault
function
{fill: (d, i) => colorAssign(this._id(d, i), linkedColorDefaults(this)), r: 3}

Shape config for the Circle shapes drawn by the lineMarkers method.

lineMarkersbooleanDefault unknown

Draws circle markers on each vertex of a Line.

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.

shapeConfigd3plusconfig

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.

stackOffsetstring | stackoffsetfnDefault stackOffsetDiverging

Sets the vertical offset applied to stacked series. Accepts a named offset — "diverging" (default), "none", "expand", "silhouette", or "wiggle" — or a custom offset function. Unknown names warn and fall back to "diverging". If value is not specified, returns the current stack offset function.

stackOrderstackorderinputDefault stackOrderTotalDescending

Sets the order of stacked series, from the bottom of the stack upward. Accepts: - a named order: "descending" (default) / "ascending" by summed value, "key" / "keyReverse" alphabetically by series key, "none" / "data" for input order, or d3's "insideOut", "appearance", "reverse"; - an Array of series keys for an explicit order; - a value accessor, or a {value, order} config, to rank series by an aggregate of any data field.

Unknown named strings warn and fall back to "descending". If value is not specified, returns the current stack order.

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.

tooltipConfigtooltipconfigDefault barTooltipConfig

Configuration for the tooltip component.

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.