简体   繁体   English

d3 v4:堆叠嵌套数据?

[英]d3 v4: Stacking nested data?

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. 将此数据嵌套在id会给出嵌套数据,其中id为键, 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: 我需要的是一个堆叠图表,显示id 1有两个类型A和一个B类出现,id 2有一个,等等。这是我正在使用的代码:

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 . 我希望这些百分比因此是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. 然而,这给了我空堆栈值,大概是因为我希望堆栈函数使用的type字段隐藏在values数组中。 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}] ). 使用stack调用的.value函数,我可以看到它所看到的数据确实是每个嵌套数组的整个数据块(即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... 我只是不知道如何使用该函数来告诉它开始计算type属性...

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 . 我首先设置键,然后使用rollupnest函数中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/ JSFiddle - https://jsfiddle.net/do4ym1L2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM