Resources for using multiple graphs in D3.js, from #knightD3 teachers / students

Based on questions from myself and other students, teachers and students of the #knightD3 MOOC have provided some resources that provide examples on how to do this:

http://www.jeromecukier.net/blog/2012/05/28/manipulating-data-like-a-boss-with-d3/

http://tympanus.net/codrops/2012/08/29/multiple-area-charts-with-d3-js/

https://flowingdata.com/2014/10/15/linked-small-multiples/

http://blog.webkid.io/multiple-maps-d3/

http://www.d3noob.org/2013/07/arranging-more-than-one-d3js-graph-on.html

Re: Percentage of women in STEM PhD programs, 2012
by Scott Murray, Instructor – Sunday, April 12, 2015, 4:56 PM

Looks great.

Yes, it is confusing, and in this course we haven’t talked about how to create multiple charts on a single page yet.

There are lots of ways to do this, but two main ways:

1) either create one SVG, and "draw" both of your charts within the same SVG, or

2) create a separate SVG for each chart.

When creating new elements in the page, remember that you specify where those elements should be created with your initial selection. So, in the code examples for this course, mostly we have seen something like:

var svg = d3.select("body") .append("svg") ...

This selects the <body> and creates a new <svg> within it. Once that’s done, a reference to the new <svg> is stored in the variable called ‘svg’.

So, after that, when we write:

svg.append("rect") ...

…this really means "start inside the SVG, then add a rectangle".

All this is to say that, when creating multiple charts, you need to pay attention towhere you are appending/creating new elements. Let’s say you create two totally separate SVGs:

var svg1 = d3.select("body") .append("svg") ... var svg2 = d3.select("body") .append("svg") ...

Or, less confusing variable names would be better:

var aggregateChart = d3.select("body") .append("svg") ... var degreeChart = d3.select("body") .append("svg") ...

This would make two separate SVGs, one for each of your charts. Then instead of writing svg.append()…, you would write something like:

degreeChart.append("rect") ...

…which would add a rectangle in only that second SVG.

I hope that helps!

Advertisements