Raspberry Pi: Measure, Record, Explore

Thursday, 13 December 2012

Setting up the margins and the graph area.

The part of the code responsible for defining the canvas (or the area where the graph and associated bits and pieces is placed ) is this part.
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

This is really (really) well explained on Mike Bostock's page on margin conventions here 'http://bl.ocks.org/3019563', but at the risk of confusing you here's my crude take on it.
The first line defines the four margins that surround the block where the graph proper will be.

var margin = {top: 30, right: 20, bottom: 30, left: 50},

So there will be a border of 30 pixels at the top, 20 at the right and 30 and 50 at the bottom and left respectively. Now the cool thing about how these are set up is that they use an array to define everything. That means if you want to do calculations in the JavaScript later, you don't need to put the numbers in, you just use the variable that has been set up. In this case margin.right = 20!

So when we go to the next line;
width = 600 - margin.left - margin.right,

the width of the inner block of the canvas where the graph will be drawn is 600 pixels – margin.left – margin.right or 600-50-20 or 530 pixels wide. Of course now you have another variable 'width' that we can use later in the code.

Obviously the same treatment is given to height.

Another cool thing about all of this is that just because you appear to have defined separate areas for the graph and the margins, the whole area in there is available for use. It just makes it really useful to have areas set aside for the axis labels and graph labels to go without having to juggle them and the graph proper at the same time.

So, let's have a play and change some values.

var margin = {top: 80, right: 20, bottom: 80, left: 50},
    width = 400 - margin.left - margin.right,
    height = 270 - margin.top – margin.bottom;

Here we've made the graph narrower (400 pixels) but retained the left / right margins and increased the top bottom margins while maintaining the overall height of the canvas. The really cool thing that you can tell from this is that while we shrank the dimensions of the area that we had to draw the graph in, it was still able to dynamically adapt the axes and line to fit properly. That is the really cool part of this whole business. D3 is running the in the background looking after the drawing of the objects, while you get to concentrate on how the data looks without too much maths!

The above description (and heaps of other stuff) is in the D3 Tips and Tricks document that can be accessed from the downloads page of d3noob.org.

No comments:

Post a Comment