Create A Bar Chart With D3 JavaScript

Create A Bar Chart With D3 JavaScript

In this tutorial we’re going to try our hand at creating a basic bar chart using D3 JavaScript. There are many concepts to cover, so we’ll go through them step by step. We’ll have a look at the various methods from the D3 library that enable us to create these striking visuals such as selection.selectAll(),, selection.enter(), selection.append(), d3.scale.linear(), d3.scale.linear().domain(), d3.scale.linear().range(), d3.scale.ordinal(), d3.scale.ordinal().domain(), d3.scale.ordinal().rangeBands() and more. Let’s jump right into the code and see what we can accomplish.

Create A Bar Chart With D3 JavaScript

Nice Work! That’s a decent looking bar chart for our first stab at it. There are actually a few tricky things to be aware of here when understanding how D3 constructs the data here. Everything may look pretty straightforward by simply reading the code above, right up until you reach the point of selecting rectangles that are not yet there! Observe this list.

To really understand how all of this works, read the documentation for all four links above. In addition, Mike Bostock the genius behind D3, wrote this tutorial to help understand how these methods work with each other to create the magic that D3 does. This helps to piece together the concept of being able to select elements that do not yet exist in the DOM, and then programmatically create said elements and update them with dynamic data like in this basic bar chart example.

Change The Data Powering The Bar Chart

Just to show that indeed the chart is rendering based on the values provided in the chartdata variable, we can change up the values in that array and observe the updated bar chart that gets created.

The Bar Chart Decoded

Walking through the code with words will help further decode how this works. First we set up the variables to hold the data we are going to work with in this particular bar chart.

  • chartdata an array of numeric values that power the length of each bar
  • height a single numeric value containing the height of the SVG
  • width a single numeric value holding the width of the SVG
  • barWidth a single numeric value holding the width of each bar
  • barOffset a single numeric value holding the space between bars

The first part of this is pretty easy. It follows the same format we have been using for the past several tutorials.

This grabs the div with the id of #bar-chart and simply appends an SVG to it, setting the width and height to the values provided in our variables listed above. We also give the bar chart a pleasing background color in this step. What comes next however is where your mind breaks a little when it realizes you shouldn’t be able to select elements not yet created.

In simple English, the above snippet says to iterate over all of the values contained in the chartdata array and for each piece of data, append a rectangle tag associated with it. Once all pieces of data have been iterated over and each <rect> has been appended, then select them all. So in a sense, you would almost expect the .selectAll() method to be last, but this is how we write this declarative approach in D3. Declarative means to just declare what you want, not how to go about getting it. Another example of the declarative style is found in how SQL works.

The next snippet of JavaScript just a touch more advanced. Let’s go through it.

If you’re still fairly new to JavaScript, and the above looks like hieroglyphics to you – fear not. In simple English, all that is happening here is we are applying a style to each rectangle, or bar, as it gets inserted into the SVG area. In addition, we set four attributes on each bar. It makes sense that each bar needs a width, a height, an x coordinate, and a y coordinate. Recall, the x coordinate determines where each bar is located on the SVG area from left to right while the y coordinate determines where the bar is placed in terms of top and bottom on the SVG area. In fact, suppose we did not include the y coordinate, what would happen? Well remember that the y coordinate is determined from the top down, so without it, we’d only have the left/right location data. Observe.

Interesting. Without specifying the y coordinate, it looks like everything starts from the top down. Therefore, in order to get the right value for the y coordinate, we need to calculate the difference between the height of the SVG container, and the height (or length if you will) of the bar. The best way to cement this home is to plug the code into your own sandbox and simply hack away at the values and observe the results in the browser. One other trick to remember what x and y refer to is to think, “x to the left, y to the sky.” This helps to remember the fact that x is the horizontal line, and y is the vertical line. Why are those two always so easy to mix up?!

Introducing Linear and Ordinal Scales

One thing that this chart lacks so far is the ability to scale properly. D3 provides a way to deal with fitting given data sets within a given range and takes care of all of the complex mathematical calculations for you. Let’s go ahead and add a y scale to the chart instead of having it hard coded. This way the full chart area is used most efficiently. These are the methods we will make use of:

Very nice – we can see that now, the bar with the largest value takes up the entire range of vertical space on the chart, while the other bars scale in relation to this. Excellent. This is a bit more efficient and elegant than the hard coded y axis version.

Factoring In Horizontal Scaling

Let’s now add a different type of scale to the horizontal, or left to right, spacing of the chart. As it stands now, only the given amount of values provided in the chartdata variable will fit evenly into the chart. What happens if the amount of values in the array is doubled? The bars will go right off the chart and no longer be visible. We can fix this with the following methods:

Using Colors With Linear Scaling

If you would like to make your chart more visually appealing, you can so do by applying colors to the bars instead of just one solid color. Let’s see how to use the linear scale method to do this now.

Add Events To Your Bar Chart

Let’s spice up our bar chart just a bit. Now check this out, we’re going to add some simple mouseover and mouseout events to trigger each individual bar to change colors when moving over it.

Note: Move your mouse over this chart!

Applying D3 Transitions

D3 has an incredible ability to create what is called a Transition, which means to apply operators and attributes in a smooth and consistent way over time, rather than immediately. This is used to create visually stunning effects and animation. We’ll use the following four methods.

To see just a simple transition in action, click the button here.

Click To Apply D3 Transition

Here is the code to recreate the transition effect.

Adding Horizontal and Vertical Guides

In the final iteration of our cool D3 JavaScript Bar Chart, we’ll simply add horizontal and vertical guides to the bar chart. In addition, we’ll add some margins to add a bit of visual space to the layout.

Click To Apply Horizontal and Vertical Guides

Here is the code for the final iteration of our bar chart.

Create A Bar Chart With D3 JavaScript Summary

This was a fun tutorial the covered a lot of ground. In the episodes prior to this, we learned the basics of configuring D3 and working with basic SVG graphics. This tutorial helped us to piece the various concepts together to create a functioning bar chart. By tweaking the code here, you may be able to figure out a way to add meaningful charts to your own applications and websites.

Leave a Reply