Most basic heatmap in d3.js

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

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

  • A dummy dataset has been created for this example, at the long format. (3 columns: row, col, value).

  • The first step is to build scales and axis. Thus each entity will have a position on the grid.

  • A scaleBand() is used, which allows to control the size of each square using the padding property. If padding is close from 1, square are very small. (0 for very big)

  • Finally, each square can be added using a rect element.
<!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: 30, bottom: 30, left: 30},
  width = 450 - margin.left - margin.right,
  height = 450 - - 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 + "," + + ")");

// Labels of row and columns
var myGroups = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
var myVars = ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10"]

// Build X scales and axis:
var x = d3.scaleBand()
  .range([ 0, width ])
  .attr("transform", "translate(0," + height + ")")

// Build X scales and axis:
var y = d3.scaleBand()
  .range([ height, 0 ])

// Build color scale
var myColor = d3.scaleLinear()
  .range(["white", "#69b3a2"])

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

      .data(data, function(d) {return':'+d.variable;})
      .attr("x", function(d) { return x( })
      .attr("y", function(d) { return y(d.variable) })
      .attr("width", x.bandwidth() )
      .attr("height", y.bandwidth() )
      .style("fill", function(d) { return myColor(d.value)} )



Related blocks →