0

I am currently taking my first steps in D3 data visualisation. So far, the D3 tutorials have helped me a lot. The pie chart tutorial http://bl.ocks.org/mbostock/3887235 though does not further explain the necessary data structure for pie charts.

My data is more complex than the label/value structure of the example. I have the annual total import data and import data of a specific good stored in JSON:

var data = [{"year":"2001","total_import":"100000","import_specific_good":"25000"},{"year":"2002",...}];

If I understand the tutorial correctly pie() iterates over the SAME entry of each DIFFERENT object.

What if I need specific DIFFERENT values of the SAME object?

I am not interested in a pie showing all annual total imports as portions, but the annual import of a specific good as a portion of the annual total import. My values would be 1. (total_import - import_specific_good) and 2. import_specific_good.

Is my proposed data structure correct for what I want to do? Or do I have to restructure everything so that the values for every year are stored in a separate variable?

var data_2001 = [{"label":"Total Import","value":"100000"},{"label":"Import of Specific Good","value":"25000"}];

var data_2002 = [{"label": ...}];

1 Answers1

0

You don't have to use a specific data structure -- you can (and will need to anyway) modify the example so you can use anything you like! So you can use your first JSON just fine. As you have only 2 values to show, you could simply construct the structure to pass to .data() on the fly.

// for pie chart
...data([json[index].total_import - json[index].import_specific_good,
         json[index].import_specific_good])...
...
// similarly for the labels

I would advise to store the numbers as numbers (e.g. without quotes) in your JSON though -- otherwise you'll have to convert them to numbers in Javascript.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • This makes sense to me concerning the data() function. But what about `var pie = d3.layout.pie() .sort(null) .value(function(d) { return WHAT COMES HERE?; });`? What do I do with the pie() function? PS: Thanks for the hint about string/integer. – Abang_Chris Mar 04 '13 at 14:32
  • If you call `pie()` with the data as above (i.e. the actual numbers), you don't need to specify `.value()`. – Lars Kotthoff Mar 04 '13 at 14:36
  • Thank you! That did the trick. Since I have a lot of data, I can now iterate over my original json and create a pie chart for each year. Very convenient! – Abang_Chris Mar 04 '13 at 15:10
  • Just for comprehension: all values I provide to pie() will be added up and scaled to 100%/360 degress, right? That means the values within pie() represent my input domain while the 360 degrees represent my output range. Did I get this correctly? – Abang_Chris Mar 05 '13 at 08:12
  • Yes. It's basically a convenience function that provides, among other things, this. – Lars Kotthoff Mar 05 '13 at 09:10