How to create a Bar Chart using D3.js

Randy Hyun
3 min readFeb 19, 2021

--

If you are trying to implement data visualization into your application, D3 is the way to go. D3 gives you flexibility to create a wide arrangement of graphs using HTML, CSS and SVG

DataSet

First off, we will need a data set. In this example we will be using JSON, but there are other alternative that could be used.

We will later see that having an array of objects will be easy to managed through mapping.

Preparation

We will need to add a script in our HTML page to access all of D3’s features (line 5)

Once we have our D3 library set in place we will start by creating the foundations of our graph. We will start by setting the width, heights, and margins, as well as a container called SVG to hold our bar graph

How this works is that you select a specific tag we want to place our graph, in our case it is the div with the id “SelectedDivForGraph” which we had in our HTML file. Once we select that we create an SVG container and add a couple attributes to it.

Limits

Now that we have it all set up we are going to set the limits for each axis.

We are setting the limits using a domain that is dependent of our dataset. For our x axis we are setting it to how many elements that we have in our data. For our y axis we are setting it to 25% (line 45) more that our highest vote count (line 40–44)

Creation

Now that the parameters of our graph are all set up, we are going to get into the meat of the graph, creating the bars itself and the axis.

For the bars itself, we will be adding color to it as well as accessing the data to manage rectangles used to create our bars. This is used with a couple attributes x and y as well as the heights and widths to guide how many and how large the bars should be. We also make functions for the axis for them to use the limits we have created previously.

Once we have all that done we just need to add a couple more lines to draw out the graphs onto our application. We first create both axis then finally the bars itself. Once this is all done, we should have a functional bar graph ready to be used.

Conclusion

Hope this simple guide is a good start of getting into the tech of data visualization using D3. This is just one of many graphs that could be created. The possibilities are endless even for a bar graph, so get graphing and find the best ways to implement data visualization onto your applications.

--

--