Very Simple Line Graph With D3

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:

See the Pen Very Simple Line Graph with D3 by Mike Newell (@newshorts) on CodePen.

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:

var svgElem = state.svg[0][0];
  var width = svgElem.offsetWidth;
  var height = svgElem.offsetHeight;

Then we get the min,max of each set of data. In this case we get min/max for x and y datasets.

var extentX = d3.extent(, function(d) { return d.x });
  var extentY = d3.extent(, function(d) { return d.y });

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:

var scaleX = d3.time.scale().range([state.padding, width - state.padding]);
  var scaleY = d3.scale.linear().range([height - state.padding, state.padding]);

Once we have our data ranges and scales, we can create our line:

var line = d3.svg.line()
    .x(function(d) { return scaleX(d.x); })
    .y(function(d) { return scaleY(d.y); })

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.

function(d) { return scaleX(d.x); }

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:

draw: function() {[]).append('g').append("path").attr("d", line);

Leave a Reply

Your email address will not be published. Required fields are marked *