Most basic stacked barplot in d3.js

This post describes how to build a very basic stacked barplot with d3.js. You can see many other examples in the barplot section of the gallery. Learn more about the theory of boxplots in

Barplot 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.

  • The d3.stack() function is used to stack the data: it computes the new position of each group on the Y axis

  • The output of d3.stack() can be used to create a set of rect as for a normal barplot.
<!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: 20, left: 50},
    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 + "," + + ")");

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

  // List of groups = what we want on the X axis
  var keys =, function(d){return(}).keys()
  var subgroups =, function(d){return(d.subgroup)}).keys()

  // Add X axis
  var x = d3.scaleBand()
      .domain(keys)       // This is what is written on the Axis: from 0 to 100
      .range([0, width])                       // This is where the axis is placed: from 100 px to 800px
    .attr("transform", "translate(0," + height + ")")

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, 200])
    .range([ height, 0 ]);

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

  // Need to nest = group the data first.
  var nestedData = d3.nest()
    .key(function(d) { return; })
    .rollup(function(d) { console.log(d) ; return d.subgroup; })

  // And then to stack the data by subgroups
  var stackedData = d3.stack()
    .value(function(d, key){


Related blocks →

  • Simple Box Plot Example in d3.js v4.0 - link

  • D3.js Boxplot with Axes and Labels - link