I have a bunch of data that can be nested into a few categories, eg:
{id: 1, type: A},
{id: 2, type: A},
{id: 1, type: B},
{id: 1, type: A},
{id: 2, type: B}
Nesting this data on id
gives me nested data with id
as the key and a values
array which contains all original values. What I need is a stacked chart showing that id 1 has two type A and one type B occurrences, id 2 has one of each, etc. This is the code I'm using:
var nested = d3.nest()
.key( function(d) {
return d.Id
})
.entries(data);
var stack = d3.stack()
.keys(['A','B'])
.offset(d3.stackOffsetExpand);
I want these as percentages hence the stackOffsetExpand
. However this is giving me null stack values, presumably because the type
field that I want the stack function to use is hidden inside the values
array. Using the .value
function of the stack
call I can see that the data it's seeing is indeed the whole chunk of data for each nested array (ie key: 1, values: [{all objects with id 1 here}]
). I just don't know how to use that function to tell it to start counting on the type
property...
This is one way to calculate the percentage from your data. I'm setting the keys first and then rolling up the values in the nest
function using rollup
. Then, I'm calculating the percentage for each key after that.
var raw_data = [{id: 1, type: "A"},
{id: 2, type: "A"},
{id: 1, type: "B"},
{id: 1, type: "A"},
{id: 2, type: "B"}];
var data = d3.nest()
.key(function(d) {return d.id;})
.rollup(function(d) { return d.length; })
.entries(raw_data);
data.forEach(function(d) {
d.percentage = d.value / raw_data.length;
console.log(d.key + ": " + d.percentage*100);
});
JSFiddle - https://jsfiddle.net/do4ym1L2/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.