Inline Labels
A multi-series line chart of apple and banana harvest data over seven years uses inline labels placed directly on each data point to show the values. The code, written in D3 v4, positions label text for each point and then calculates a white background rectangle behind it using `getBBox()` to improve legibility. Series names are appended to the final label of each line via a `tspan`, with colors assigned by `d3.scaleCategory10`. Data is loaded from a TSV file using `d3.requestTsv` and parsed with `d3.timeParse`.
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/ramnathv/'>ramnathv</a>'s block: <a href='http://bl.ocks.org/ramnathv/9a40b378be7ca09c4e4b'>Inline Labels</a>