Most basic stacked area chart in d3.js

This post describes how to build a very basic stacked area chart with d3.js. A stacked area chart allows to visualize the evolution of a numeric variable for several groups. You can see many other examples in the stacked area chart section of the gallery. Learn more about the theory of stacked area chart in

Stacked area section


  • The Html part of the code just creates a div that will be modified by d3 later on.

  • The first part of the javascript code set a svg area. It specify the chart size and its margin. Read more.

  • Data is available here. It shows the evolution of baby names in the US. Note that it is a long format: 3 columns only.

  • To build a stacked area chart, data must be stacked, using the d3.stack() function.

  • Once the new coordinates are available, shapes can be added through path, using the d3.area() helper.
<!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: one array for each value of the X axis.
  var sumstat = d3.nest()
    .key(function(d) { return d.year;})

  // Stack the data: each group will be represented on top of each other
  var mygroups = ["Helen", "Amanda", "Ashley"] // list of group names
  var mygroup = [1,2,3] // list of group names
  var stackedData = d3.stack()
    .value(function(d, key){
      return d.values[key].n

  // 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; })*1.2])
    .range([ height, 0 ]);

  // color palette
  var color = d3.scaleOrdinal()

  // Show the areas
      .style("fill", function(d) { name = mygroups[d.key-1] ;  return color(name); })
      .attr("d", d3.area()
        .x(function(d, i) { return x(; })
        .y0(function(d) { return y(d[0]); })
        .y1(function(d) { return y(d[1]); })


Related blocks →