SVG to D3 code HT @maartenzam; by @nadiehbremer


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:

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 ="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 ="body") .append("svg") ... var svg2 ="body") .append("svg") ...

Or, less confusing variable names would be better:

var aggregateChart ="body") .append("svg") ... var degreeChart ="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!