Skip to main content
100%

Inline Labels

✓ Published0🌍 Public
Mmbostock
Last edited Oct 11, 2019
Created on Jan 12, 2016

This example demonstrates a multi-series line chart where each data point is labeled directly on the line, with the final point of each series showing the series name in bold. The chart reads from a TSV file using `d3.requestTsv` and `d3.timeParse` for dates. The code uses `d3.line` to draw the paths, scales `d3.scaleTime` and `d3.scaleLinear` for axes, and `d3.scaleCategory10` for colors. For each label, `element.getBBox` computes the text bounding box, and a white rectangle is drawn behind it with padding for legibility.

AI-generated description

This 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.

gpl-3.0 Licensed

Similar vizzes