Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 44 ยท Shapes and Paths

Line Charts and Curves with d3.line

Draw line charts with d3.line: time scales, accessors x and y, curve types, defined() for gaps, multiple series with grouping, dots.

Bars and circles are elements you create one per datum. A line is different: one <path> element represents the whole series. Its shape is stored in the d attribute as a string such as M10,80L50,20L90,60. Writing that string by hand is painful, so D3 offers a shape generator: d3.line() is a function that takes your data array and returns the path string.

How shape generators work

A generator has accessor methods that tell it where to find x and y in each datum, and configuration methods such as curve. You build it once and call it with data:

JavaScript
const line = d3.line()
  .x(d => x(d.date))
  .y(d => y(d.value));

line(data);   // "M12,95L40,60L70,72..."

Then you set that string on a path. Remember the rule from Binding Data: a line needs the whole array in one element, so use datum() (or pass the string directly), not a join:

JavaScript
g.append("path")
  .datum(data)
  .attr("fill", "none")
  .attr("stroke", "steelblue")
  .attr("stroke-width", 2)
  .attr("d", line);       // line is called with the datum

Remember fill="none": a path is filled by default, and an unfilled line would show a black polygon.

A time-series line chart

Curves

By default points are joined with straight segments (curveLinear). The .curve() method switches the interpolation. The most useful ones:

Curve Character
d3.curveLinear Straight lines (default, most honest)
d3.curveMonotoneX Smooth, never overshoots the data in y (safe for charts)
d3.curveBasis Very smooth B-spline that does not pass through the points
d3.curveCardinal, d3.curveCatmullRom Smooth through every point; may overshoot
d3.curveNatural Natural cubic spline through the points
d3.curveStep, curveStepBefore, curveStepAfter Staircase, good for values that hold until the next change
d3.curveBumpX S-shaped connections, nice for flow charts

Smoothing is a design decision, not just decoration. A smooth curve can suggest values between samples that never existed, and curveBasis can drift away from the data, so use curveMonotoneX or plain linear for serious charts.

Comparing curve types

Gaps and missing values: defined()

If your data has holes (null, NaN, a sensor that failed), the line should break there rather than plunge to zero. Use line.defined(fn). Points for which the function returns false are skipped and the line is split into separate segments.

JavaScript
const line = d3.line()
  .defined(d => d.value != null && !Number.isNaN(d.value))
  .x(d => x(d.date))
  .y(d => y(d.value));

Multiple series

For several lines, structure the data as an array of series, and create one path per series. A grouping helper makes that easy: d3.group(data, d => d.name) from a flat table. Then bind each series (as the datum of its path) with a normal join, and call line with the series' values.

Several series with gaps and direct labels

The Lima path has two M (moveto) commands: the missing 2019 value splits the line into two pieces. Direct labels at the line ends replace a legend, which is easier to read.

Styling lines

  • stroke-width 1.5 to 3 reads well; stroke-linejoin="round" removes sharp spikes at corners.
  • stroke-dasharray="4 3" makes a dashed line for forecasts or comparison series.
  • Use vector-effect="non-scaling-stroke" if a transform scales the path but you want a constant thickness.
  • Add markers (small circles) only when points are sparse; hundreds of dots become clutter.

For hover behavior (a guide line and tooltip that follows the mouse using bisector), see Mouse Events and Tooltips.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does d3.line()(data) return?

    A shape generator is a function from data to a path string, which you assign with .attr('d', ...).
  2. 2. Why does a line path need fill='none'?

    SVG fills open paths as if they were closed. Setting fill none shows just the stroke.
  3. 3. How do you make a line break at missing values?

    defined tells the generator which points exist. Undefined points end one segment and begin the next.
  4. 4. Which curve is a safe choice for smooth lines that never overshoot the data?

    curveMonotoneX preserves monotonicity in y, so it does not invent peaks that the data lacks.

Summary

  • d3.line() converts an array to a path d string; configure x, y, curve and defined.
  • Use one path per series with datum, fill="none" and a stroke; group tidy data with d3.group.
  • Pick curves deliberately: linear or monotone for charts, step for held values.
  • defined() breaks lines at gaps; direct labels beat legends for a handful of lines.

Next: Area and Stacked Charts