Drawing the Heatmap
Learn how to draw a heatmap with D3.
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:
async function draw(el) {// Dataconst dataset = await d3.json('/udata/W96VkQJkGG5/data-5-3.json')// Dimensionslet dimensions = {width: 600,height: 150,};// Draw Imageconst svg = d3.select(el).append("svg").attr("width", dimensions.width).attr("height", dimensions.height)// Rectanglessvg.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
async function draw(el) {// Dataconst dataset = await d3.json('/udata/W96VkQJkGG5/data-5-3.json')// Dimensionslet dimensions = {width: 600,height: 150,};// Draw Imageconst svg = d3.select(el).append("svg").attr("width", dimensions.width).attr("height", dimensions.height)// Rectanglessvg.append('g').selectAll('rect').data(dataset).join('rect').attr('stroke', 'black').attr('stroke', '#ddd')}draw('#heatmap1')
After ...