I’ve been learning more about D3 and decided to apply what I learned about composition to make a very simple line graph. I’ll just post the pen and comment on it below:
Basically, the important parts are that I’m using a factory to create “LineGraph()”. It takes some data, a class name of the actual svg element to target and some default options. Once you call, “lineGraph.draw()” the real work begins.
First we get the dimensions of the svg element on the page:
Then we get the min,max of each set of data. In this case we get min/max for x and y datasets.
We also need to tell the graph how to scale the data to actual dimensions of the graph itself. This is done by plugging the width and height of the graph into a function d3 can use to scale our data points. We also add some padding so the data doesn’t touch the edge of the graph and get cut off. Moar on scaling here: http://www.d3noob.org/2012/12/setting-scales-domains-and-ranges-in.html
Once we have our data ranges and scales, we can create our line:
In many cases, d3 will return a function you’ve prepared before hand to run on some data. In this case we prepare a line. You can see we pass functions into the x and y values.
These functions are used by d3 to “loop the data” and the return value is what the actual data value is set to. So we use our scale functions here to scale the x and y values after we have pulled them out of each object. We then return the scaled value to the loop.
Finally, we set up our “draw()” method, when called, will draw the actual line on the graph: