Small multiple for line chart

Displaying more than a few groups on the same linechart most of the time result in a spaghetti plot that is almost unreadable. Using small multiple is a very good alternative, and this post describes how to implement it in d3.js.

Lineplot section


  • This is an advance technique. You probably need to understand how to build a basic line plot first, and then a lineplot with several groups.

  • Instead of building one main svg area as usual, many svg areas are created: one per group

  • To do so, data is bound to each svg area. This is very handy: each time a component will be created, it will be done for each subchart

  • ToDo: improve explanation
<!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: 30, right: 0, bottom: 30, left: 50},
    width = 210 - margin.left - margin.right,
    height = 210 - - margin.bottom;

//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;})

  // What is the list of groups?
  allKeys ={return d.key})

  // Add an svg element for each group. The will be one beside each other and will go on the next row when no more room available
  var svg ="#my_dataviz")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + + margin.bottom)
            "translate(" + margin.left + "," + + ")");

  // 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 color = d3.scaleOrdinal()

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

  // Add titles
    .attr("text-anchor", "start")
    .attr("y", -5)
    .attr("x", 0)
    .text(function(d){ return(d.key)})
    .style("fill", function(d){ return color(d.key) })


Related blocks →