Line plot with several groups

This post describes how to build a line chart with several groups. Mind the Spaghetti chart: it becomes unreadable when too many lines are displayed. More examples of line charts in the dedicated section.

Line chart section


  • First of all, it is important to understand how to build a basic line chart with d3.js.

  • Here, the data is in long (or tidy) format: one numerical columns provides the information of each group.

  • Thus, the first step is to use the d3.nest function to group the variable. Read more about it here.

  • Next steps are pretty usual: building axis, color scales and lines.
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src=""></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>


// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - - margin.bottom;

// append the svg object to the body of the page
var svg ="#my_dataviz")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + + margin.bottom)
          "translate(" + margin.left + "," + + ")");

//Read the data
d3.csv("", function(data) {

  // group the data: I want to draw one line per group
  var sumstat = d3.nest() // nest function allows to group the calculation per level of a factor
    .key(function(d) { return;})

  // Add X axis --> it is a date format
  var x = d3.scaleLinear()
    .domain(d3.extent(data, function(d) { return d.year; }))
    .range([ 0, width ]);
    .attr("transform", "translate(0," + height + ")")

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, d3.max(data, function(d) { return +d.n; })])
    .range([ height, 0 ]);

  // color palette
  var res ={ return d.key }) // list of group names
  var color = d3.scaleOrdinal()

  // Draw the line
        .attr("fill", "none")
        .attr("stroke", function(d){ return color(d.key) })
        .attr("stroke-width", 1.5)
        .attr("d", function(d){
          return d3.line()
            .x(function(d) { return x(d.year); })
            .y(function(d) { return y(+d.n); })



Related blocks →