Search⌘ K

Drawing the Heatmap

Explore how to draw a heatmap using D3.js by creating and organizing rectangles in a group element. Understand how to set attributes for color, size, and position to arrange 100 squares in a 5 by 20 grid. This lesson helps you grasp foundational techniques for building heatmap layouts and preparing for dynamic color scaling.

We'll cover the following...

We are going to begin drawing the heatmap. A heatmap is a set of squares organized in a grid. We are going to focus on drawing the squares. The first few steps have been taken care of. We can proceed to draw the squares after drawing the image. We’ll update our script to the following:

Javascript (babel-node)
async function draw(el) {
// Data
const dataset = await d3.json('/udata/W96VkQJkGG5/data-5-3.json')
// Dimensions
let dimensions = {
width: 600,
height: 150,
};
// Draw Image
const svg = d3.select(el)
.append("svg")
.attr("width", dimensions.width)
.attr("height", dimensions.height)
// Rectangles
svg.append('g')
.selectAll('rect')
.data(dataset)
.join('rect')
}
draw('#heatmap1')

We are creating a new group. The shapes for the heatmap will be drawn in a group to keep our code organized. After appending the <g> element, we are making an empty selection with the selectAll() method for <rect> elements.

Presently, there are not any rectangles. We are making an empty selection because we want to join the data with the selection. The data will end up in the enter selection. We will be able to loop through this selection.

After selecting, we are chaining the data() function with the dataset array. Lastly, we are chaining the join() function to start drawing the <rect> elements.

There are 100 items in the array, so we should find 100 rectangles in the document. We will look at the output in a moment. First, there are a couple of attributes we should add.

Adding color

Javascript (babel-node)
async function draw(el) {
// Data
const dataset = await d3.json('/udata/W96VkQJkGG5/data-5-3.json')
// Dimensions
let dimensions = {
width: 600,
height: 150,
};
// Draw Image
const svg = d3.select(el)
.append("svg")
.attr("width", dimensions.width)
.attr("height", dimensions.height)
// Rectangles
svg.append('g')
.selectAll('rect')
.data(dataset)
.join('rect')
.attr('stroke', 'black')
.attr('stroke', '#ddd')
}
draw('#heatmap1')
...