Small multiple for area chart

If you have several groups to display on your area chart, it is possible to stack them. But it makes it harder to study the evolution of each group separately. Using small multiple is a very good alternative, and this post describes how to implement it in d3.js.

Area chart section


  • This is an advance technique. You probably need to understand how to build a basic area chart first, and then have a look to the lineplot with several groups to understand how nesting works.

  • 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", function(d){ return color(d.key) })
        .attr("stroke", "none")
        .attr("d", function(d){
          return d3.area()
          .x(function(d) { return x(d.year) })
          .y1(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 →