Multi-Line Graph: Purpose, Code, and Description

Learn how to create multi-line graphs to represent different data on the same graph.

We'll cover the following

Purpose

Creating a multi-line graph is a pretty handy thing to be able to do, and we worked through an example earlier in the course as an extension of our simple graph. In that example, we used a CSV file that had the data arranged with each line’s values in a separate column.

date,close,open
1-May-12,68.13,34.12
30-Apr-12,63.98,45.56
...

This is a common way to have data stored. But if you are retrieving information from a database, you may not have the luxury of having it laid out in columns. It may be presented in a more linear fashion where each line’s values are stored on a unique row with the identifier for the line on the same row. For instance, the data above could just as easily be presented as follows:

price,date,value
close,1-May-12,68.13
close,30-Apr-12,63.98
...

In this case, we would need to “pivot” the data to produce the same multi-column representation as the original format. This is not always easy, but it can be achieved using the d3.group function, which we will examine.

As well as this, we will want to automatically encode the lines to make them different colors and add a legend with the line name and the color of the appropriate line.

Finally, because we will build a graph script that can cope with any number of lines (within reason), we will need to be able to show/hide the individual lines to try and clarify the graph if it gets too cluttered.

All of these features have been covered individually in the book, so what we’re going to do is combine them in a way that presents us with an elegant multi-line graph that looks a bit like this:

Get hands-on with 1400+ tech skills courses.