Raspberry Pi Pico Tips and Tricks

Tuesday, 25 December 2012

Adding data to a line function in d3.js

The following post is a portion of the D3 Tips and Tricks document which it free to download from the main page. To use this post in context, consider it with the others in the blog or just download the pdf :-)
--------------------------------------------------------------------------
We're getting towards the end of our journey through the script now. The next step is to get the information from the array 'data' and to place it in a new array that consists of a set of coordinated that correspond to the points we are going to plot.

var valueline = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.close); });

Now I'm aware that the statement above may be somewhat ambiguous. You would be justified in thinking that we already had the data stored and ready to go. But that's not strictly correct.

What we have is data in a raw format, we have added pieces of code that will allow the data to be adjusted for scale and range to fit in the area that we want to draw, but we haven't actually taken our raw data and adjusted it for our desired coordinates. That's what the code above does.

The main function that gets used here is the d3.svg.line() function. This function uses assessor functions to store the appropriate information in the right area and in the case above they use the x and y assessors (that would be the bits that are '.x' and '.y'). The d3.svg.line() function is called a 'path generator' and this is an indication that it can carry our some pretty clever things on its own accord. But in essence its job is to assign a set of coordinates in a form that can be used to draw a line.

So each time this line function is called on, it will go through the data it is pointed to and it will assign coordinates to 'date' and 'close' pairs using the 'x' and 'y' functions that we set up earlier (which of course are responsible for scaling and setting the correct range / domain).

Of course, it doesn't get the data all by itself, we still need to actually call the valueline function with 'data' as the source to act on. But never fear, that's coming up soon.

No comments:

Post a Comment