Do you need a dynamic bar chart like this in your web page, with positive and negative values, and categories along the x-axis?
Dog breeds are on my mind at the moment as we just bought a new Sheltie puppy – this chart might show a person’s scores for each breed. Click the button above to see the next person’s (random) set of scores.
<script src="http://d3js.org/d3.v3.min.js"></script> <script src="barChart.js"></script> <script> var points = [['Beagle',-10], ['Terrier',30], ['Sheltie',55], ['Greyhound',-24]]; var myChart = d3.elts.barChart().width(300); d3.select("body").datum(points).call(myChart); </script>
Please check out the source code for
barChart.js on bitbucket.
You may also find this helpful even if you don’t need a barchart, but want to understand how to build a reusable chart. I was inspired when I read Mike Bostock’s exposition, Towards reusable charts, but I found it took some work to get my head around how to do it for real – so I hope this example may help others too.
The key tricks were:
- How to adjust Mike Bostock’s sample code to produce bars instead of a line and area
- Where the
enter(), update and
exit()fit in (answer: they are internal to the reusable function)
- How to call it, including whether to use
datum(answer: see code snippet above)
- How to refer to the x and y coordinates inside the function (answer: the function maps them to d and d regardless of how they started out)
You can find a much fancier version of this chart, with a range slider and hover text, in this post.