D3.js multiseries bar graph with clickable legend tutorial

Infographic ideas are way more popular than Georgia news, according to the humble record that is the visitor log here at greencracker.net. So, here’s a post to nerd out with. It’s a beginner-intermediate graph tutorial.  By “tutorial,” I mean heavily-commented code, pretty much.

If this helps you, great!  It’s payback for all the great help I’ve found from other folk. Why not visit them:  D3 Tips and Tricks, Scott Murray, D3 Vienno & Christophe Viau, to name a few.

This is what we’ll make: 


 


Full, commented working example here

.CSV here

Hi!  So, first thing, let me tell you how the page is laid out because it’s a little different than most tutorials. It contains two (2!) svgs.  No need to code just yet, this is an FYI.

Screen Shot 2014-10-06 at 9.16.54 AM


 

Why have 2 svgs?  For me, it was for layout purposes.  I wanted some responsive design, so this seems to me the better solution than an earlier draft.

Screen Shot 2014-10-06 at 9.05.15 AM


OK now the coding starts. Let’s start with the html.

Put all the classes in the body:

Screen Shot 2014-10-06 at 9.19.36 AM

Then let’s get into javascript with some declarations, most rather standard. Most interesting thing?  No y-axis.

Screen Shot 2014-10-06 at 9.50.43 AM


The next hunk reads in the data and wrangles it into a form D3 can use:

Screen Shot 2014-10-06 at 9.54.14 AM 

Next how about a legend?
Screen Shot 2014-10-06 at 9.57.33 AM

Now the world’s most simple change function. This is what makes the transition nice-looking. If this were not here and you just depended on the redraw() function, the graph would change in a non-visually pleasing way, like a powerpoint slide without a transition applied.

Screen Shot 2014-10-06 at 10.54.27 AM

So finally let’s start drawing some bars.  This is the world’s simplest enter-append-exit sequence. You can fancy it  up here if you like.

Screen Shot 2014-10-06 at 10.58.54 AM

Screen Shot 2014-10-06 at 11.00.09 AM

I hope this has helped! Drop a comment if I can help.

Be the first to comment on "D3.js multiseries bar graph with clickable legend tutorial"

Leave a comment

Your email address will not be published.


*



*