Data structure for D3 pie charts

天涯浪子 提交于 2019-12-12 02:58:00

问题


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:


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.



来源:https://stackoverflow.com/questions/15200095/data-structure-for-d3-pie-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!