Adding More Than One Line to a Graph

Learn to add multiple lines to the graph.

All right, we’re starting to get serious now. Two lines on a graph is a bit of a step into a different world in one respect. I mean that in the sense that there’s more than one way to carry out the task, and I tend to do it one way and not the other. This is mainly because I don’t fully understand the other way.

Note: That’s not because it’s more complex or that it’s a bad way. It’s just that once I started doing things one way, I haven’t come across a need to do things another way. There’s a good chance I will have to revisit this decision in the future. But for now, I’ll keep moving.

Changing the data

How are we going to do this? I think that the best way will be to make the executive decision that we have suddenly come across more data, and it is also in our data.csv file, which we’ll rename data2.csv just to highlight the difference between the two data sets.

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

There are three columns: date, open, and close. The first two are exactly what we have been dealing with all along, and the last (open) is our new made-up data. Each column is separated by a comma (hence, .csv (comma separated values)), which is the format we’re currently using to import data.

We should save this as a new file, so we don’t mess up our previous data (as mentioned earlier). Let’s call it, data2.csv.

We will build our new code using our simple graph template to start with. The immediate consequence of this is that we need to edit the line that was looking for data.csv to reflect the new name.

d3.csv("data2.csv").then(function(data) {

So when you browse to our new graph’s HTML file, we don’t see any changes. It still happily loads the new data. But because it hasn’t been told to do anything with it, nothing new happens.

Drawing the second line

What we need to do now is essentially duplicate the code blocks that drew the first line for the second line.

The good news is that, in the simplest way possible, that’s just two code blocks. The first sets-up the function that defines the new line:

Get hands-on with 1400+ tech skills courses.