Bar Chart Wrap Up
05 May 2015Now that you’ve had a chance to play with the bar chart example(s) I thought I would point you in the direction of some futher reading and a bit of code that may help with the Have a play! section.
In the CSS:
- Change the spacing of the bars
- Change the colour of the bars (Googling ‘HTML color names’ may help, or use a hex #FFFFFF colour)
Both of these involve changing the CSS portion of the code. The padding
and margin
properties specifically. In terms of colour options there are a great many web resources that can help with the selection of hex (i.e. #0000FF) and named colours (i.e. steelblue), but one such resource I’m quite fond of is Adobe Color CC which allows you to create colour schemes (which can really help when creating visualisations). Click to ‘edit’ any of the colour schemes and it will give you the hex value for each colour.
In the JavaScript:
- Change the size of the graph
This is primarily contolled by the .range()
JavaScript method (which in this case dictates how much space the x-axis has). You can also control the graph’s height by changing the padding
and margin
CSS properties.
- What other options are there other than
d3.scale.linear
?
Lots according to the API specification, but have a look at how the shape of the graph changes if you change d3.scale.linear
to d3.scale.pow
and d3.scale.sqrt
. Changing which scale is used changes how the .domain()
maps to the .range()
, an important consideration.
- What about adding a filter so that only certain bars above a certain value are displayed?
D3.js has a built in filter method that allows selections to be limited to items that pass a certain condition. So in this case, under the .enter().append("div")
line in the JavaScript, I added .filter(function(d) { return d > 15})
which limits further processing (in this case styling and the addition of text) to only those elements whose value is greater than 15. Because of the way the code in the example is structured, the graph does leave some whitespace in expectation of these bars being present.
- Can you make the bars below 15 red and the ones above green?
There are quite a few ways which this could be achieved. I opted to remove the background-color: steelblue;
line from the CSS, and add .style("background-color", function(d) {return (d > 15 ? "green" : "red")})
to the JavaScript under the other .style()
method. In my function I’ve used what is called a tenary operator which is a short-hand way of encapulating a simple if-then-else statement, basically (thing-to-test ? true-value : false-value). You’ll see these quite a bit in D3.js examples as D3 relies heavily on inline functions which can get a bit of a readability bump from these short-hand forms.
Here’s what mine looked like (adjusted to d > 14 so you can see the colouring):
And the code for it: