-->

dc.js pie chart sum example

2019-07-23 17:30发布

问题:

I have records like this :

{
{"Pass": "10", "Fail": "20", "Untested": "40"}
{"Pass": "20", "Fail": "40", "Untested": "50"}
{"Pass": "30", "Fail": "50", "Untested": "60"}
...
}

Obviously, total = pass + fail + untested. I want to sum up each of these values and then finally show a pie chart using dc.js that shows total Pass, total Fail, total Untested. I couldnt find a good example.

In the example below, each record is converted to a binary loss/gain value. Then the pie chart shows the aggregated loss/gain. I need to aggregate at the collection level, not individual record level. How can I do that ?

Any help is much appreciated.

Ref:

http://nickqizhu.github.io/dc.js/

回答1:

Take a look at the example in this jsfiddle

The trick is to modify your input data, so that you can create an dimension for all records on the result. So the data should look like this:

[{"result":"Pass","value":"10","_id":0},
{"result":"Fail","value":"20","_id":0},
{"result":"Untested","value":"40","_id":0},
{"result":"Pass","value":"20","_id":1},
{"result":"Fail","value":"40","_id":1},
{"result":"Untested","value":"50","_id":1},
{"result":"Pass","value":"30","_id":2},
{"result":"Fail","value":"50","_id":2},
{"result":"Untested","value":"60","_id":2}] 

I did this using a new js library I just created called melt, but it would be fairly simple to duplicate the same logic yourself. Also here is another example in a recent user list discussion.