Although you can see lots of amazing charts in the home page of d3, d3 doesn’t ship with any pre-built chart function. In this post, I am going to draw a simple animated bar chart using d3. The output will be:
Let’s start by creating a simple bar chart, we will be creating it based on the following tutorial: http://alignedleft.com/tutorials/d3/making-a-bar-chart
The tutorial explains clearly on to how to make a simple bar chart, following is a fiddle I created, with just some modification as I preferred:
Note what have be added:
|
As an example, I am actually making the scales
myself here, in pratice we should use d3’s pre-defined scales to help us on this.
Adding animation to the chart
Too add animation in d3, we will use transition
. To do this, it is as simple as to just assign an initial value to our chart attributes.
Then, we assign the final values (which is, what we already have) to the chart and applies transition.
The attributes that have to be animated are:
– y
of the rectangles
– height
of the rectangles
So, let’s set an initial value to 0
of our y
and height
.
Therefore, we can keep our existing attributes of x
, width
and fill
(color) of the chart. The code becomes:
|
Fixing the bottom down bar chart
Notice the animation we have is a bottom down chart. So, why is it not bottom up?
It is because, the y
start from 0
and increase downwardly.
Therefore when we set your y
to start from 0
, it’s actually moving the bar downwardly too.
So in order to fix this, we should on the other hand, set y
to it’s largest value, which is, the cavans height
!
|
Now we have a bar chart animating bottom up!