Inline Labels
This example demonstrates a multi-series line chart with inline data labels, showing values for Apples and Bananas across several years. Every point is labeled directly on the line, with a white rectangle behind the text to ensure legibility, computed via SVG’s `getBBox` and a small padding. The chart is built with D3 v4 Alpha, using `d3.requestTsv` to load data, `d3.scaleTime` and `d3.scaleLinear` for axes, and `d3.line` for path generation. The final label in each series appends the series name as a bold `tspan`.
AI-generated descriptionThis example shows how to implement Ann K. Emery’s technique of placings labels directly on top of a line in D3 4.0 Alpha.
To construct the multi-series line chart, the data is first transformed into separate arrays for each series. (The series names are automatically derived from the columns in the TSV file, thanks to a new dsv.parse feature.)
var series = data.columns.slice(1).map(function(key) {
return data.map(function(d) {
return {
key: key,
date: d.date,
value: d[key]
};
});
});
A label is rendered for each point in each series. Beneath this label, a white rectangle is added, whose size and position is computed automatically using element.getBBox plus a little bit of padding. The resulting label is thus legible. The last label for each series gets an additional tspan to show the series name.
forked from <a href='http://bl.ocks.org/mbostock/'>mbostock</a>'s block: <a href='http://bl.ocks.org/mbostock/4b66c0d9be9a0d56484e'>Inline Labels</a>