How to draw charts using d3

Sebastian Ravenscroft
3 min readMay 9, 2021

--

d3 is an amazing UI tool that gives you a huge amount of flexibility. d3 is a JavaScript library designed to product all kinds of data visualisations.

This means it’s a little more work to actually get up and running but once you do it’s very powerful. Just take a look at Mike Bostok’s gallery for some inspiration!

https://observablehq.com/@d3/gallery

How d3 works

d3 is usually used to create dynamic SVG images which you can then style using CSS.

If you haven’t worked with SVG images then take a moment to inspect any SVG image in your browser. You’ll see it contains a set of instructions for drawing the image which look a lot like HTML. This is what lets use scale SVG images without pixelation.

d3 code style is a little different to what you’ll see with typical UI frameworks. It uses a chain of methods which are the steps needed to handle your data and draw the chart. And it also makes use of callback functions and helpers from the d3 library. It’s best to take a few examples and go with the flow, it will quickly make sense.

Drawing a basic chart

Start by making a new index.html file and paste this code snippet:

This is just a plain HTML page where we pull in the latest version of d3 (version 6) via their CDN.

Now in the same directory create a main.js file where we can write our code:

At first glance this looks a bit confusing but bear with it. We call the drawBarChart() method with a target HTML container element, the chart dimensions, and our dataset.

Now we use d3 helper methods to define two callback functions called xScale and yScale.

Given a y-axis value, the yScale() callback will return a scaled height for the bar on the chart.

Given an x-axis key, the xScale() callback returns the x position where we should draw the corresponding bar.

Finally we have the big block of code which draws the chart. The first part selects our HTML element and appends an SVG which is where we will draw the chart. It sets the dimensions of the chart and then uses the .data() method to bind our dataset to the chart.

Next we use the .enter() method to loop over our data points. All the following chained commands refer to a single data point, and are used to draw a single bar.

We use the xScale.bandwidth() method to get the width of a single bar in our chart.

The height of the bar is simply calculated by calling the yScale() callback against the value of the data point. The y position is measured from the top of the chart, essentially the white space above the bar.

Finally create a style.css file in the same directory with some basic styling:

Update your index.html file to pull in the CSS file:

And that’s it we’re done!

Open your index.html file in your web browser and you should see something that looks like this.

--

--