Basic contour chart

This post describes how to build a very basic contour chart with d3.js. The contour chart is a representation of a 2d density. It is made thanks to the d3-contour plugin. Visit for more theoretical info on 2d density charts.

2d density section


  • The Html part of the code just creates a div that will be modified by d3 later on. It also load the d3-contour plugin

  • The input dataset has 2 numeric variables: x and y. A 2d density plot basically represents the amount of data point on each part of the grid.

  • The d3-contour plugin allows to compute the density using d3.contourDensity(). It's important to play with the bandwidth() argument to find the good resolution.

  • Finally, paths can be drawn using d3.geoPath()
<!DOCTYPE html>
<meta charset="utf-8">

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

<!-- specific plugin -->
<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: 20, right: 30, bottom: 30, left: 40},
    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 data
d3.csv("", function(data) {

  // Add X axis
  var x = d3.scaleLinear()
    .domain([5, 20])
    .range([ 0, width ]);
    .attr("transform", "translate(0," + height + ")")

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

  // compute the density data
  var densityData = d3.contourDensity()
    .x(function(d) { return x(d.x); })   // x and y = column name in .csv input data
    .y(function(d) { return y(d.y); })
    .size([width, height])
    .bandwidth(20)    // smaller = more precision in lines = more lines

  // Add the contour: several "path"
      .attr("d", d3.geoPath())
      .attr("fill", "none")
      .attr("stroke", "#69b3a2")
      .attr("stroke-linejoin", "round")

Related blocks →