LinePlot
Creates a line plot based on an array of data.
Basic example
Section titled “Basic example”A minimal line plot: groupBy splits the data into one line per id, with x and y mapping each point’s position.
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",
};
Line labels
Section titled “Line labels”Set lineLabels: true to print each series name at the end of its line, letting you trace a color straight to its label without consulting a legend.
const config = {
data: [
{id: "alpha", x: 4, y: 9},
{id: "alpha", x: 5, y: 17},
{id: "alpha", x: 6, y: 13},
{id: "beta", x: 4, y: 17},
{id: "beta", x: 5, y: 8},
{id: "beta", x: 6, y: 16},
{id: "gamma", x: 4, y: 14},
{id: "gamma", x: 5, y: 9},
{id: "gamma", x: 6, y: 11},
],
groupBy: "id",
lineLabels: true,
x: "x",
y: "y",
};
Custom line labels
Section titled “Custom line labels”Override the default series-name label via shapeConfig.Line.label — here a function returns each line’s final y value, so the tip of every line reports its latest number.
const config = {
data: [
{id: "alpha", x: 4, y: 9},
{id: "alpha", x: 5, y: 17},
{id: "alpha", x: 6, y: 13},
{id: "beta", x: 4, y: 17},
{id: "beta", x: 5, y: 8},
{id: "beta", x: 6, y: 16},
{id: "gamma", x: 4, y: 14},
{id: "gamma", x: 5, y: 9},
{id: "gamma", x: 6, y: 11},
],
groupBy: "id",
lineLabels: true,
shapeConfig: {
Line: {
label: function (d) {
const dataArray = this._filteredData.filter(f => f.id === d.id);
const maxX = Math.max(...dataArray.map(f => f.x));
const maxData = dataArray.find(f => f.x === maxX);
return `${maxData.y}`;
},
},
},
x: "x",
y: "y",
};
Line labels both
Section titled “Line labels both”Set lineLabels: "both" to name each line at both ends, and lineLabelConfig: {value: true} to add each end’s value, formatted like the y axis’s ticks (set valueFormat to format it yourself). The plot makes room on the left for the first labels, and labels that would overlap are spread apart on each side, with a dotted connector back to their line. "start" labels only the left end, and true (or "end") only the right.
const renewables = {
Brazil: [41, 42, 43, 45, 44, 46, 47, 46, 48, 47],
Chile: [30, 31, 33, 34, 36, 35, 37, 38, 37, 36],
Peru: [31, 32, 31, 30, 31, 29, 30, 31, 30, 30],
Colombia: [28, 29, 28, 30, 29, 28, 27, 28, 27, 27],
Ecuador: [29, 30, 30, 31, 32, 31, 30, 29, 29, 29],
Mexico: [17, 18, 18, 19, 20, 20, 21, 21, 22, 22],
};
const config = {
data: Object.entries(renewables).flatMap(([country, shares]) =>
shares.map((share, i) => ({country, year: 2015 + i, share})),
),
groupBy: "country",
legend: false,
lineLabels: "both",
lineLabelConfig: {value: true},
x: "year",
y: "share",
yConfig: {
tickFormat: d => `${d}%`,
},
};
Secondary y axis
Section titled “Secondary y axis”Plot a second metric against a right-hand axis with y2; because growth lives on a different scale than trade value, y2Config.tickFormat renders it as a percentage independent of the left axis.
const config = {
data: [
{
"Country ID": "nausa",
Country: "United States",
Year: 2011,
"Trade Value": 1403273708182,
"Trade Value Growth": 0.17509765715100706,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2012,
"Trade Value": 1453520657725,
"Trade Value Growth": 0.03580694860170724,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2013,
"Trade Value": 1478035757057,
"Trade Value Growth": 0.016866013703836988,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2014,
"Trade Value": 1521969928619,
"Trade Value Growth": 0.029724701416885744,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2015,
"Trade Value": 1409516953687,
"Trade Value Growth": -0.07388646307488954,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2016,
"Trade Value": 1353648792022,
"Trade Value Growth": -0.0396363885647921,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2017,
"Trade Value": 1456201053251,
"Trade Value Growth": 0.07575987348669187,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2018,
"Trade Value": 1548849519602,
"Trade Value Growth": 0.06362340292513889,
},
{
"Country ID": "nausa",
Country: "United States",
Year: 2019,
"Trade Value": 1511931053052,
"Trade Value Growth": -0.023836057720756986,
},
],
groupBy: "Country",
time: "Year",
x: "Year",
y: "Trade Value",
y2: "Trade Value Growth",
y2Config: {
tickFormat: d => `${parseInt(d * 100)}%`,
},
};
Line vertex markers
Section titled “Line vertex markers”Enable lineMarkers: true to draw a circle at every data point, sized here to radius 6 via lineMarkerConfig.r so individual observations stand out.
Draws circle markers on each vertex of a Line.
Changing vertex marker style
Section titled “Changing vertex marker style”Pass functions to lineMarkerConfig (r and opacity) to style markers per datum — here only each line’s final point (x === 6) is drawn large and fully opaque to spotlight the endpoints.
const config = {
data: [
{id: "alpha", x: 4, y: 9},
{id: "alpha", x: 5, y: 17},
{id: "alpha", x: 6, y: 13},
{id: "beta", x: 4, y: 17},
{id: "beta", x: 5, y: 8},
{id: "beta", x: 6, y: 16},
{id: "gamma", x: 4, y: 14},
{id: "gamma", x: 5, y: 9},
{id: "gamma", x: 6, y: 11},
],
groupBy: "id",
lineMarkers: true,
lineMarkerConfig: {
opacity: d => (d.x === 6 ? 1 : 0.25),
r: d => (d.x === 6 ? 6 : 4),
},
x: "x",
y: "y",
};
Changing splining
Section titled “Changing splining”Set shapeConfig.Line.curve to "catmullRom" to interpolate a smooth spline through the points instead of connecting them with straight segments.
const config = {
data: [
{fruit: "apple", price: 5, year: 2014},
{fruit: "banana", price: 4, year: 2014},
{fruit: "apple", price: 7, year: 2015},
{fruit: "banana", price: 6, year: 2015},
{fruit: "apple", price: 10, year: 2016},
{fruit: "banana", price: 8, year: 2016},
{fruit: "apple", price: 6, year: 2017},
{fruit: "banana", price: 10, year: 2017},
{fruit: "apple", price: 8, year: 2018},
{fruit: "banana", price: 15, year: 2018},
],
groupBy: "fruit",
shapeConfig: {
Line: {
curve: "catmullRom",
},
},
x: "year",
y: "price",
};
Changing stroke width
Section titled “Changing stroke width”Thicken every line with shapeConfig.Line.strokeWidth when you want the trend to read boldly at a glance.
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: {
Line: {
strokeWidth: 5,
},
},
x: "x",
y: "y",
};
Confidence intervals
Section titled “Confidence intervals”Supply confidence as a [lower, upper] pair of accessors to draw a shaded margin-of-error band around each line; confidenceConfig.fillOpacity keeps that region translucent. Hovering lists each line’s bounds after its value.
const config = {
data: [
{fruit: "apple", year: 1, amount: 50, moe: 2},
{fruit: "apple", year: 2, amount: 56, moe: 1},
{fruit: "apple", year: 3, amount: 58, moe: 1},
{fruit: "banana", year: 1, amount: 88, moe: 3},
{fruit: "banana", year: 2, amount: 90, moe: 4},
{fruit: "banana", year: 3, amount: 76, moe: 3},
],
groupBy: "fruit",
confidence: [d => d.amount - d.moe, d => d.amount + d.moe],
confidenceConfig: {
fillOpacity: 0.3,
},
x: "year",
y: "amount",
};
Nested confidence bands
Section titled “Nested confidence bands”Give confidence a list of bands, outermost first, to nest several intervals around each line. Each band is a [lower, upper] pair, optionally with a label third; the widest draws lightest and the narrowest darkest (see confidenceConfig.bandOpacity). Hovering a single point lists each band’s range under its label. For forecasts, see FanChart.
const config = {
data: [
{id: "alpha", year: 2020, value: 40, p10: 34, p90: 47, p25: 37, p75: 43},
{id: "alpha", year: 2021, value: 46, p10: 38, p90: 55, p25: 42, p75: 50},
{id: "alpha", year: 2022, value: 44, p10: 35, p90: 54, p25: 40, p75: 49},
{id: "alpha", year: 2023, value: 51, p10: 40, p90: 63, p25: 46, p75: 57},
{id: "alpha", year: 2024, value: 55, p10: 42, p90: 69, p25: 49, p75: 62},
{id: "beta", year: 2020, value: 22, p10: 18, p90: 27, p25: 20, p75: 24},
{id: "beta", year: 2021, value: 25, p10: 19, p90: 31, p25: 22, p75: 28},
{id: "beta", year: 2022, value: 30, p10: 23, p90: 37, p25: 27, p75: 33},
{id: "beta", year: 2023, value: 28, p10: 20, p90: 36, p25: 24, p75: 32},
{id: "beta", year: 2024, value: 33, p10: 24, p90: 43, p25: 29, p75: 38},
],
groupBy: "id",
confidence: [
["p10", "p90", "80%"],
["p25", "p75", "50%"],
],
x: "year",
y: "value",
};
Trend line
Section titled “Trend line”Each line gets its own trend line and, with trendLineConfig.confidence, a shaded confidence band in its color. On a time axis the fit runs over the dates, so the tooltip shows R² and the number of observations but no equation.
const config = {
data: [
{id: "alpha", date: "2018-01-01", value: 31},
{id: "alpha", date: "2019-01-01", value: 38},
{id: "alpha", date: "2020-01-01", value: 35},
{id: "alpha", date: "2021-01-01", value: 44},
{id: "alpha", date: "2022-01-01", value: 49},
{id: "alpha", date: "2023-01-01", value: 47},
{id: "alpha", date: "2024-01-01", value: 56},
{id: "beta", date: "2018-01-01", value: 52},
{id: "beta", date: "2019-01-01", value: 49},
{id: "beta", date: "2020-01-01", value: 55},
{id: "beta", date: "2021-01-01", value: 51},
{id: "beta", date: "2022-01-01", value: 54},
{id: "beta", date: "2023-01-01", value: 58},
{id: "beta", date: "2024-01-01", value: 57},
],
groupBy: "id",
time: "date",
x: "date",
y: "value",
trendLine: true,
trendLineConfig: {confidence: true},
};
Trend line projection
Section titled “Trend line projection”trendLineConfig.projection extends each trend line past the end of its data, widening the axis to fit. Give it {to} an end value (here the year 2030) or a number of steps. The projected stretch draws dotted, and a linear fit’s confidence band opens into a wider prediction interval: the range a future value is likely to fall in, which grows the further out it reaches. Hover the plot over a projected year to compare every series’ projected value and range. The projected stretch is marked as a forecast (a shaded backdrop, a rule, and a “Forecast” label); set forecast: false to leave it unmarked.
const config = {
data: [
{id: "alpha", date: "2018-01-01", value: 31},
{id: "alpha", date: "2019-01-01", value: 38},
{id: "alpha", date: "2020-01-01", value: 35},
{id: "alpha", date: "2021-01-01", value: 44},
{id: "alpha", date: "2022-01-01", value: 49},
{id: "alpha", date: "2023-01-01", value: 47},
{id: "alpha", date: "2024-01-01", value: 56},
{id: "beta", date: "2018-01-01", value: 52},
{id: "beta", date: "2019-01-01", value: 49},
{id: "beta", date: "2020-01-01", value: 55},
{id: "beta", date: "2021-01-01", value: 51},
{id: "beta", date: "2022-01-01", value: 54},
{id: "beta", date: "2023-01-01", value: 58},
{id: "beta", date: "2024-01-01", value: 57},
],
groupBy: "id",
time: "date",
x: "date",
y: "value",
trendLine: true,
trendLineConfig: {
confidence: true,
projection: {to: 2030},
},
};
Trend line projection steps
Section titled “Trend line projection steps”A number projects that many steps past the last value, at the data’s own spacing: here 5 more years. Dates step by their calendar interval (years, quarters, months, days…). Any fit type projects, and projectionConfig styles the projected stretch over the line’s own styles. Hover a projected line for its value at the nearest projected year.
const config = {
data: [
{id: "Solar", year: 2017, value: 12},
{id: "Solar", year: 2018, value: 15},
{id: "Solar", year: 2019, value: 19},
{id: "Solar", year: 2020, value: 22},
{id: "Solar", year: 2021, value: 28},
{id: "Solar", year: 2022, value: 34},
{id: "Solar", year: 2023, value: 41},
{id: "Wind", year: 2017, value: 30},
{id: "Wind", year: 2018, value: 32},
{id: "Wind", year: 2019, value: 33},
{id: "Wind", year: 2020, value: 37},
{id: "Wind", year: 2021, value: 38},
{id: "Wind", year: 2022, value: 41},
{id: "Wind", year: 2023, value: 42},
],
groupBy: "id",
x: "year",
y: "value",
trendLine: "exponential",
trendLineConfig: {
projection: 5,
projectionConfig: {strokeDasharray: "1 4", strokeWidth: 3},
},
};
Dashed lines
Section titled “Dashed lines”Return a different dash pattern per series from shapeConfig.Line.strokeDasharray to distinguish lines by stroke style rather than color alone.
const config = {
data: [
{fruit: "apple", price: 5, year: 2014},
{fruit: "banana", price: 4, year: 2014},
{fruit: "cherry", price: 7, year: 2014},
{fruit: "apple", price: 7, year: 2015},
{fruit: "banana", price: 6, year: 2015},
{fruit: "cherry", price: 9, year: 2015},
{fruit: "apple", price: 10, year: 2016},
{fruit: "banana", price: 8, year: 2016},
{fruit: "cherry", price: 5, year: 2016},
{fruit: "apple", price: 6, year: 2017},
{fruit: "banana", price: 10, year: 2017},
{fruit: "cherry", price: 10, year: 2017},
{fruit: "apple", price: 8, year: 2018},
{fruit: "banana", price: 15, year: 2018},
{fruit: "cherry", price: 12, year: 2018},
],
groupBy: "fruit",
shapeConfig: {
Line: {
strokeDasharray: d => {
if (d.fruit === "apple") return "10";
if (d.fruit === "banana") return "10 7 3";
if (d.fruit === "cherry") return "10 7 5 2";
return "0";
},
},
},
x: "year",
y: "price",
};
Custom line colors
Section titled “Custom line colors”Return a color per series from shapeConfig.Line.stroke to override the automatic palette with your own meaningful hues.
const config = {
data: [
{fruit: "apple", price: 5, year: 2014},
{fruit: "banana", price: 4, year: 2014},
{fruit: "cherry", price: 7, year: 2014},
{fruit: "apple", price: 7, year: 2015},
{fruit: "banana", price: 6, year: 2015},
{fruit: "cherry", price: 9, year: 2015},
{fruit: "apple", price: 10, year: 2016},
{fruit: "banana", price: 8, year: 2016},
{fruit: "cherry", price: 5, year: 2016},
{fruit: "apple", price: 6, year: 2017},
{fruit: "banana", price: 10, year: 2017},
{fruit: "cherry", price: 10, year: 2017},
{fruit: "apple", price: 8, year: 2018},
{fruit: "banana", price: 15, year: 2018},
{fruit: "cherry", price: 12, year: 2018},
],
groupBy: "fruit",
shapeConfig: {
Line: {
stroke: d => {
if (d.fruit === "apple") return "green";
if (d.fruit === "banana") return "goldenrod";
if (d.fruit === "cherry") return "red";
return "grey";
},
},
},
x: "year",
y: "price",
};
Fill between
Section titled “Fill between”fillBetween shades the area between two lines in the color of whichever is higher, switching exactly where they cross, so a trade surplus and deficit read at a glance. Name the pair by series id, pass true for the first two series, or give a list of pairs.
const config = {
data: [
{id: "Exports", year: 2016, value: 120},
{id: "Imports", year: 2016, value: 132},
{id: "Exports", year: 2017, value: 131},
{id: "Imports", year: 2017, value: 136},
{id: "Exports", year: 2018, value: 145},
{id: "Imports", year: 2018, value: 139},
{id: "Exports", year: 2019, value: 152},
{id: "Imports", year: 2019, value: 141},
{id: "Exports", year: 2020, value: 138},
{id: "Imports", year: 2020, value: 129},
{id: "Exports", year: 2021, value: 141},
{id: "Imports", year: 2021, value: 150},
{id: "Exports", year: 2022, value: 149},
{id: "Imports", year: 2022, value: 166},
{id: "Exports", year: 2023, value: 163},
{id: "Imports", year: 2023, value: 170},
{id: "Exports", year: 2024, value: 181},
{id: "Imports", year: 2024, value: 172},
],
groupBy: "id",
fillBetween: ["Exports", "Imports"],
x: "year",
y: "value",
};
Temperature range
Section titled “Temperature range”A min/max range: fillBetween: true fills between the first two series. fillBetweenConfig styles the fill, and its accessors receive the higher series’ row with above and below keys naming the pair, so the A > B and B > A regions can be colored apart (here gray, or red if the low ever rose above the high).
const config = {
data: [
["Jan", -3, -12],
["Feb", -1, -11],
["Mar", 5, -5],
["Apr", 13, 2],
["May", 20, 8],
["Jun", 25, 14],
["Jul", 28, 17],
["Aug", 27, 16],
["Sep", 22, 11],
["Oct", 14, 5],
["Nov", 6, -1],
["Dec", -1, -8],
].flatMap(([month, high, low]) => [
{id: "High", month, temperature: high},
{id: "Low", month, temperature: low},
]),
groupBy: "id",
color: d => (d.id === "High" ? "#e8590c" : "#1c7ed6"),
fillBetween: true,
fillBetweenConfig: {
fill: d => (d.above === "High" ? "#868e96" : "#e03131"),
fillOpacity: 0.2,
},
x: "month",
y: "temperature",
};
Sorting lines
Section titled “Sorting lines”With thick, round-capped strokes the lines overlap, so shapeConfig.sort sets the draw order — here forcing apple to render on top of the others.
const config = {
data: [
{fruit: "apple", price: 5, year: 2014},
{fruit: "banana", price: 4, year: 2014},
{fruit: "apple", price: 7, year: 2015},
{fruit: "banana", price: 6, year: 2015},
{fruit: "apple", price: 10, year: 2016},
{fruit: "banana", price: 8, year: 2016},
{fruit: "apple", price: 6, year: 2017},
{fruit: "banana", price: 10, year: 2017},
{fruit: "apple", price: 8, year: 2018},
{fruit: "banana", price: 15, year: 2018},
],
groupBy: "fruit",
shapeConfig: {
Line: {
strokeLinecap: "round",
strokeWidth: 10,
},
sort: (a, b) => (a.fruit === "apple" ? 1 : -1),
},
x: "year",
y: "price",
};
Dotted line predictions
Section titled “Dotted line predictions”Give forecast a function that flags the predicted rows. Here each flow’s prediction is its own series (grouped by ["Type", "Flow"]) that starts at the last observed year: its line is dashed, the observed history stays solid, and the forecast stretch gets a shaded backdrop, a rule at its start, and a translated “Forecast” label. Rows flagged within one series work too: the line dashes from its last unflagged point. Style or hide each piece with forecastConfig.
const config = {
data: [
{
Year: 2016,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 363829206796,
Type: "Observed",
},
{
Year: 2016,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 364493560621,
Type: "Observed",
},
{
Year: 2017,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 376297646785,
Type: "Observed",
},
{
Year: 2017,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 401741532115,
Type: "Observed",
},
{
Year: 2018,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 414829536859,
Type: "Observed",
},
{
Year: 2018,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 441736801029,
Type: "Observed",
},
{
Year: 2019,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 425699639802,
Type: "Observed",
},
{
Year: 2019,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 432693158563,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 366314124058,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 406070750072,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 366314124058,
Type: "Predicted",
},
{
Year: 2020,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 406070750072,
Type: "Predicted",
},
{
Year: 2021,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 346314124058,
Type: "Predicted",
},
{
Year: 2021,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 386070750072,
Type: "Predicted",
},
{
Year: 2022,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 336314124058,
Type: "Predicted",
},
{
Year: 2022,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 396070750072,
Type: "Predicted",
},
],
forecast: d => d.Type === "Predicted",
groupBy: ["Type", "Flow"],
time: "Year",
x: "Year",
y: "Trade Value",
};
Forecast start
Section titled “Forecast start”A discrete-axis value (a year, or a date on a time axis) starts the forecast at that point for every line. forecastConfig relabels the backdrop and sets the dash of each line’s forecast stretch.
const config = {
data: [
{
Year: 2016,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 363829206796,
Type: "Observed",
},
{
Year: 2016,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 364493560621,
Type: "Observed",
},
{
Year: 2017,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 376297646785,
Type: "Observed",
},
{
Year: 2017,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 401741532115,
Type: "Observed",
},
{
Year: 2018,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 414829536859,
Type: "Observed",
},
{
Year: 2018,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 441736801029,
Type: "Observed",
},
{
Year: 2019,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 425699639802,
Type: "Observed",
},
{
Year: 2019,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 432693158563,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 366314124058,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 406070750072,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 366314124058,
Type: "Predicted",
},
{
Year: 2020,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 406070750072,
Type: "Predicted",
},
{
Year: 2021,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 346314124058,
Type: "Predicted",
},
{
Year: 2021,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 386070750072,
Type: "Predicted",
},
{
Year: 2022,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 336314124058,
Type: "Predicted",
},
{
Year: 2022,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 396070750072,
Type: "Predicted",
},
].filter(d => d.Type === "Observed"),
forecast: 2018,
forecastConfig: {label: "Projection", lineDasharray: "2 4"},
groupBy: "Flow",
time: "Year",
x: "Year",
y: "Trade Value",
};
Reference lines and bands
Section titled “Reference lines and bands”On a time axis, referenceLines and referenceBands take dates (a Date, a year, or a date string) and "Callout" annotations anchor at a date and value. Reference values widen the axis to stay in view (callouts do not), and everything zooms and pans with the axes.
const config = {
data: [
{
Year: 2016,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 363829206796,
Type: "Observed",
},
{
Year: 2016,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 364493560621,
Type: "Observed",
},
{
Year: 2017,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 376297646785,
Type: "Observed",
},
{
Year: 2017,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 401741532115,
Type: "Observed",
},
{
Year: 2018,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 414829536859,
Type: "Observed",
},
{
Year: 2018,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 441736801029,
Type: "Observed",
},
{
Year: 2019,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 425699639802,
Type: "Observed",
},
{
Year: 2019,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 432693158563,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 366314124058,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 406070750072,
Type: "Observed",
},
{
Year: 2020,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 366314124058,
Type: "Predicted",
},
{
Year: 2020,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 406070750072,
Type: "Predicted",
},
{
Year: 2021,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 346314124058,
Type: "Predicted",
},
{
Year: 2021,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 386070750072,
Type: "Predicted",
},
{
Year: 2022,
"Flow ID": 1,
Flow: "Imports",
"Trade Value": 336314124058,
Type: "Predicted",
},
{
Year: 2022,
"Flow ID": 2,
Flow: "Exports",
"Trade Value": 396070750072,
Type: "Predicted",
},
].filter(d => d.Type === "Observed"),
groupBy: "Flow",
time: "Year",
x: "Year",
y: "Trade Value",
referenceBands: [{x: [2018, 2019], label: "Tariff escalation"}],
referenceLines: [{y: 400e9, label: "$400B", dash: true}],
annotations: [
{
shape: "Callout",
data: [{x: 2020, y: 366314124058, label: "Imports fall 14% in 2020"}],
dx: -90,
dy: 30,
maxWidth: 100,
},
],
};
Quarterly data
Section titled “Quarterly data”Point data at a remote URL to load records directly, and set time (and x) to the Quarter field so d3plus parses the quarterly periods into an ordered time axis.
Accessor function or string key for the time dimension of each data point.
Axis break
Section titled “Axis break”A single spike can squash the rest of a line. yBreak removes 70–900 from the y axis, so the everyday values keep their detail; the axis marks the break, two lines run across the plot from it, and the line is cut straight between them. Tooltips still report the real values.
const config = {
data: [
{id: "Requests", day: 1, ms: 42},
{id: "Requests", day: 2, ms: 48},
{id: "Requests", day: 3, ms: 45},
{id: "Requests", day: 4, ms: 940},
{id: "Requests", day: 5, ms: 51},
{id: "Requests", day: 6, ms: 47},
{id: "Requests", day: 7, ms: 55},
],
groupBy: "id",
x: "day",
y: "ms",
yBreak: [70, 900],
};
Connect gaps
Section titled “Connect gaps”A null value (or a step another line has and this one skips) is a gap. By default a line runs straight through it; connectGaps(false) leaves it empty, "dashed" bridges it with a short dash in the line’s color, and an object ({stroke, strokeDasharray, strokeWidth, opacity}) styles the bridge. Bridges follow the line’s curve and have no tooltip or keyboard focus; lineMarkers shows a lone point between two gaps.
const config = {
connectGaps: "dashed",
data: [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023].flatMap(
(year, k) => [
{
id: "Survey",
year,
value: [2017, 2018, 2021].includes(year) ? null : 40 + 6 * Math.sin(k),
},
{id: "Census", year, value: 30 + k * 2},
],
),
groupBy: "id",
lineMarkers: true,
x: "year",
y: "value",
};
Range breaks
Section titled “Range breaks”Daily closing prices only exist on trading days. xConfig.rangeBreaks hides weekends and the listed holidays from the time axis, so Friday sits next to Monday and the line never stretches across days with no trading. Ticks and labels stay on trading days, and hover and zoom read the broken axis. Add {hours: [16, 9.5]} for intraday data, or {bounds: [start, end]} to remove one range with a break marker.
const config = {
data: (() => {
// Jan 15 and Feb 19 are market holidays.
const holidays = [14, 49];
const out = [];
let close = 180;
for (let i = 0; i < 90; i++) {
const date = new Date(2024, 0, 1 + i);
const weekend = date.getDay() === 0 || date.getDay() === 6;
if (weekend || holidays.includes(i)) continue;
close += Math.sin(i / 6) * 2.5 + Math.cos(i / 2.3) * 1.2;
out.push({ticker: "ACME", date, close: Math.round(close * 100) / 100});
}
return out;
})(),
groupBy: "ticker",
x: "date",
xConfig: {
rangeBreaks: ["weekends", {values: ["2024-01-15", "2024-02-19"]}],
},
y: "close",
};
Range breaks trading hours
Section titled “Range breaks trading hours”{hours: [16, 9.5]} hides 4pm to 9:30am every day (the window wraps past midnight), and "weekends" hides Saturday and Sunday, so only trading hours take up width. The first tick after each hidden night is labeled with its day.
const config = {
data: (() => {
// Half-hourly prices from 9:30 to 15:30 on two weeks of trading days.
const out = [];
let price = 50;
for (let d = 0; d < 14; d++) {
const day = new Date(2024, 3, 1 + d);
if (day.getDay() === 0 || day.getDay() === 6) continue;
for (let h = 9.5; h < 16; h += 0.5) {
const date = new Date(day);
date.setHours(Math.floor(h), (h % 1) * 60);
price += Math.sin(d * 13 + h * 2) * 0.4;
out.push({ticker: "ACME", date, price: Math.round(price * 100) / 100});
}
}
return out;
})(),
groupBy: "ticker",
x: "date",
xConfig: {rangeBreaks: ["weekends", {hours: [16, 9.5]}]},
y: "price",
};
Range breaks marked range
Section titled “Range breaks marked range”{bounds: [start, end]} removes one range, here a month with no readings, and draws the axis break marker where it was. Add marker: false to close the range without a marker. Other rules repeat too often to mark, so they default to no marker.
const config = {
data: (() => {
// Daily sensor readings with June missing.
const out = [];
for (let i = 0; i < 120; i++) {
const date = new Date(2024, 4, 1 + i);
if (date.getMonth() === 5) continue;
const value = 20 + Math.sin(i / 6) * 4;
out.push({sensor: "Sensor", date, value: Math.round(value * 100) / 100});
}
return out;
})(),
groupBy: "sensor",
x: "date",
xConfig: {
rangeBreaks: {bounds: [new Date(2024, 5, 1), new Date(2024, 6, 1)]},
},
y: "value",
};
Configuration
import {LinePlot} from "@d3plus/core";
activefalse|functionThe active callback function for highlighting shapes.
annotationsunknownDefaultunknownAllows 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'sx/y(in data units, or plot-area fractions withxRef/yRef: "plot"), offset bydx/dypixels and joined to its anchor by a connector ending in an arrowhead or dot (seeCalloutAnnotation);"ReferenceLine"and"ReferenceBand"draw whatreferenceLinesandreferenceBandsentries expand into. All annotations follow zoom and never respond to the pointer or keyboard.axisPersistbooleanDefaultunknownDetermines 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
trueto 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).
baselinenumberStarts the value axis (the x axis for horizontal charts) at a value:
baseline(n)renders exactly likeyDomain([n])(orxDomain([n])). Bars, areas, and stems still grow from the chart's own0in the Plots that draw from one (such as BarChart, AreaPlot, Histogram, and Lollipop), so withbaselineBreakon (their default) the axis breaks back to a0tick and bars run through the break, with its gap cut across them, and with it off the axis stretches down to0. As withyDomain([n]), onlynis 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'sroundingis "none"), and marks for values pastnstop at the axis's edge. When every value sits at or belown, it ends the axis instead, likeyDomain([undefined, n]). A bound given inyDomain/xDomainwins. Returns the chart's own baseline when none is set.bufferboolean|recordDefaultassign({}, 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
trueorfalseto 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>|undefinedCSS 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 owntooltipConfig.className.colorDefaultscolordefaultsconfigOverrides the default colors used when assigning fills from data and choosing legible text colors:
darkandlight(the text colors picked for contrast against a background),missing(null/undefined values),on/off(true/falsevalues),sequential(the anchor hue for magnitude ramps), andscale(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.confidenceunknownThe 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
falsefor 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 (seeconfidenceConfig.tooltip). Passfalseto 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, andconfidenceConfig.bandOpacityshades 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.confidenceConfigrecordDefaultfunction{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(default2),strokeDasharray,strokeOpacity, andcapWidth: the length of each end cap, in pixels or as a percentage string of the bar's thickness (default"50%"). Keys nested underAreaorBarapply only to that shape's interval. With several bands,bandOpacitysets 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 replacesfillOpacity.tooltip(defaulttrue) 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 tofalseto leave them out. Accepted keys: any key the Area or Path shape takes at the top level, plusbandOpacity,capWidth,tooltip,Area(Area keys), andBar(Path keys andcapWidth); any other key logs a warning.configd3plusconfigMethods that correspond to the key/value pairs and returns this class.
crosshairConfigrecordDefaultfunction{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.<datapoint>|objectThe 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, andjson.If your data URL needs specific headers to be set, an Object with a "url" and "headers" (or any other
fetchrequest 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
configobject from the data formatter (including the newdataarray 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.
discreteCutoffnumberDefaultunknownWhen 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
0to disable the behavior entirely.facetstring|false|functionSplits 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
falseto draw a single chart. SeefacetConfigfor the grid's layout and shared scales.facetConfigfacetconfigConfiguration 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 (default20). -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) => stringfunction for each panel's title, orfalseto hide panel titles. -titleConfig: TextBox config for the panel titles (fontSize,fontWeight,fontColor,textAnchor,padding, …).fontFamilystring|array.<string>The font family used throughout the visualization.
groupBystring|function|array.<string|function>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.
groupPaddingnumberDefaultunknownThe pixel space between groups of bars.
highlightfalse|functionPersistently 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),highlightis a standing state that survives pointer movement. Passfalseto clear it.hoverfalse|functionThe 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.
lineMarkerConfigrecordDefaultfunction{fill: (d, i) => colorAssign(this._id(d, i), linkedColorDefaults(this)), r: 3}Shape config for the Circle shapes drawn by the lineMarkers method.
lineMarkersbooleanDefaultunknownDraws circle markers on each vertex of a Line.
localestring|objectThe 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.
onstringEvent listener for the specified event typenames. Mirrors the core d3-selection behavior.
parentunknownParent config used by the wrapper.
renderfunctionDraws 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|htmlelementThe SVG container element as a d3 selector or DOM element. Defaults to
undefined.shapeConfigd3plusconfigConfiguration object with key/value pairs applied as method calls on each shape.
sizefalse|plotaccessorargSets the size of bubbles to the given Number, data key, or function.
stackOffsetstring|stackoffsetfnDefaultstackOffsetDivergingSets 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.stackOrderstackorderinputDefaultstackOrderTotalDescendingSets 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|functionThe 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|functionAccessor for the value used in the threshold algorithm. A stacked Plot defaults to its stacked value.
timestring|false|functionAccessor function or string key for the time dimension of each data point.
timelineDefaultstring|date|array.<string|date>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|functionAccessor function or string key for the total value displayed in the visualization.
translatefunctionDefines 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.
trendLinetrendlinetypeDraws 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; seetrendLineConfigfor 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 tofalse(the default) to remove.trendLineConfigrecordOptions 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 whentrendLineis"polynomial"(default2). -confidence: draws a confidence band around a linear fit (defaultfalse). -confidenceLevel: the band's confidence level (default0.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.5more years), or to an end value with{to: 2030}(default0, 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 (defaulttrue). - Any other key (stroke,strokeWidth,strokeDasharray, …) styles the Line shape.Stacked charts always fit one line to the stack totals.
xplotaccessorargDefaultfunctiond => d["x"]Accessor function or string key for the x-axis value of each data point.
x2plotaccessorargDefaultfunctiond => 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.
xConfigrecordDefaultfunction{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.
yplotaccessorargDefaultfunctiond => d["y"]Accessor function or string key for the y-axis value of each data point.
y2plotaccessorargDefaultfunctiond => 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.
yConfigrecordDefaultfunction{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.