Plotting on the web (with Javascript D3)

We have seen how to plot a bar chart with Python, now let’s see how it can be done for the web so that it can be displayed in any (recent) browser as it is the quickest way to reach a global audience (regardless of the operating system and device type.

We will use the same data and chart as in the Python example.

To plot it, I will use the D3 library, probably the most used javascript library for web visualisation.
This small tutorial assumes that you know Javascript and the W3C DOM.Download the library from its web site and then import it by adding the following in the HTML head part:

script src="d3/d3.v3.js" type="text/javascript"

The actual Javascript code to generate the chart will go in the body part; let’s start by declaring the data set, a dictionary with name of country and its number of WHC sites:

d3.select(“body”) finds the body element in the DOM and hands off a reference to the next step in the chain (append) that is used to create a new SVG empty element and to append it into the DOM.

Finally, the reference to the DOM element is stored in a new variable myChart. This reference saved in a variable is not strictly needed but it allows not to search for that SVG each time—as in d3.select()—but to write only myChart, for example, to define the chart size (think about it as a canvas where to draw):

myChart.attr("width", 500)
.attr("height", 200);

An even better version is to put the width and height values into variables at the top of your code:

The d3 function selectAll() will return empty references to all rectangles (which don’t exist yet), while data() binds the data set to the elements we’re going to create, enter() returns a placeholder reference to the new element, and append() finally adds a rectangle (there are a number of visual elements that you can include between those SVG tags, including rect to draw a rectangle or there is circle, ellipse, line, text, and path) to the DOM.
Again, a new variable – myBars – store references to all of the rectangles / bars.

If you run this, it will just display an empty space (size 500 x 200). We need to set a couple more of attributes, such as the rectangles’ sizes and positions.

Now let’s see how we can create and display these bars: this is achieved by using the function attr() on myBars (similar as before, on the variable myChart) that is used to set the attributes of an element.
Specifically the attributes “x” and “y” (the position inside the SVG element) and the attributes “width” and “height” (the size) need to be set.

Notice that to display the bars separate among them, a variable barPadding is used that is set to the number of pixels for the space (in this case barPadding = 1).

The functions are called with two arguments: the data (d) and the index (i). Note that our dataset contains both names and values, so we must refer to the value as d.value

attr(“x”) : this is the x position; through an anonymous function it gets assigned a dynamic value that corresponds to each value’s position in the data set. And the bars are so spaced that they can fit the space allocated for the SVG element (that’s the variable w, while the function length returns the total number of data entries in the data set whcTop10).

attr(“width”): this is how wide the bars are. You can just set a constant value, such as 20 (it’s in pixels). Or (like here) you can set the bar widths to be proportional so they get narrower when more data entries are present, or wider when there are fewer values: the width will now be set as the ratio of the SVG width and the data entries, minus a padding value.

attr(“height”): this is how high are the bars. And of course this should be proportional to the data set values. This is obtained by using again an anonymous function that sets it simply to the parameter d. To make the bars well spaced, d is multiplied to a ratio that is the one between the SVG element’s height and the maximum value in the data set.

attr(“y”): this is the y position (the top of the bars); to make the bars starting from the x axes, we use an anonymous function returning the height of the SVG element minus the data entry value.

Here is how it looks like:

That’s nice but the chart looks quite bare …

To add a colour to all the bars you can apply the attribute “fill”:

// set bar colour = blue
myBars.attr("fill", "blue");

Note: of course you can achieve the same using the CSS and is actually a better way; just define a class in CSS and refer to it in the javascript code.

Instead of passing a fixed colour, you can also pass a function, for example to have different colours according to the value (the height of the bar); actually a bad idea from a visualisation prospective, but it could be used to set a different colour for a specific bar, for example for the one with the highest value:

text(): this is the function to add a text element, in this case the label. The function just returns the data value and that is what is displayed.

attr(): as for the rect element, you can set the coordinates with “x” and “y” (so that each label will be inside the related bar) and to style the text too, for example to set its colour to white. If you wish you can also set the font, its size and so on.

Here is the result:

But the real power of D3 library lies in its interactivity.

Let’s add a mouseover effect that displays the country name as a tooltip when the user goes over a bar with the mouse:

// change colour and display country name when mouse is over
myBars.on("mouseover", function(d,i) {
d3.select(myBars[0][i])
.style("fill", "red") // new colour is red
.append("title").text(function(d) { // title is browser tooltip
return "This country is " + d.name;
})
});

To do this is simply adding a function for the standard effect on(“mouseover”): you select the bar via the parameter i, change the fill style to apply a new colour (red in this case) and append the tooltip based on the d parameter.

When the user moves the mouse out, you need to change back the colour:

// change colour back when mouse is out
myBars.on("mouseout", function(d,i) {
d3.select(myBars[0][i])
.style("fill", "blue"); // back to blue
});

Welcome!

This is my personal blog, where I write about what I learned, mostly about software, project management and machine learning.
Why this name? The blog should help me to navigate into the future using (and not forgetting) the past experiences.
From Europe to the world.