Turn your data plots into visual information
Mihalis Tsoukalos explains how to create impressive visualisations with the JavaScript library D3.js and a big pile of data.
Mihalis Tsoukalos
OUR EXPERT
Mihalis Tsoukalos is a DataOps engineer and a technical writer. He’s the author of Go Systems Programming and Mastering Go. Get in touch with Mihalis at @mactsouk.
QUICK TIP
D3.js (https://d3js.org) is a low-level JavaScript library, which means that you’ll need to write lots of code even for the simplest of the examples. On the other hand, D3.js gives you absolute control over the output.
This month’s coding tutorial is on D3.js, a powerful low-level JavaScript library that can create unique, highly customisable and impressive graphical output based on your data. For reasons of simplicity most of the examples shown here will include the data that will be visualised in the HTML file that contains the JavaScript code. However, D3.js enables you to read data from text files that reside either on your local machine or online.
The D3.js (Data Driven Documents) library can be downloaded using a tag in the HTML page that contains the JavaScript code. The code processes and creates your visualisations, so there’s no need to download it locally. Additionally, you’re free to read the JavaScript code of D3.js and make any changes or improvements you want to it!
There are several advantages to using D3.js. First, it can create professional output on the fly without the need to store PNG and PDF files that you’ll have to embed into HTML code. Second, if you’re reading data from the Internet or from a local file that changes, a page refresh is enough to obtain the new data and automatically update the plots. Third, D3 can create animated and interactive graphics - and there are plenty of visualisations that can benefit from these two features. Finally, if you already know JavaScript, using D3 is straightforward as long as you’re willing to learn its rich API.
When creating plots with D3.js, bear in mind that each D3 graph requires an HTML file that contains the DOM tree and the JavaScript code for manipulating the DOM tree and the data. If you’re familiar with JavaScript you might already know that you can organise your JavaScript code using multiple files that you can call using the tag. However, this tutorial will put all JavaScript code in a single HTML file.
Drawing the canvas
The canvas is the area that you give D3 for drawing. It can be shorter than the browser windows, which is the norm. Note that the coordinates of the upper left corner of the canvas are always (0,0) whereas the coordinates of the bottom left corner are (0, height), whatever the value of the height variable is. The coordinates of the upper right corner are (width, 0), based on the value of the width variable, and the coordinates of the bottom right corner of the canvas are (width, height).