gpt4 book ai didi

angular - d3 - 使用 nest/group 创建查找

转载 作者:行者123 更新时间:2023-12-04 15:18:32 24 4
gpt4 key购买 nike

使用 d3.js 库,我想像这样创建一个查找:

var lookup = d3.nest()
.key((d: any) => d.day)
.rollup((leaves: any) => {
return d3.sum(leaves, (d: any) => { return parseInt(d.count); }) as any;
})
.object(dateData);

所以我可以稍后使用它:

rect.filter(function (d) { return d in lookup; })
.style("fill", function (d) { return d3.interpolatePuBu(scale(lookup[d])); })
.select("title")
.text((d) => this.titleFormat(new Date(d)) + ": " + lookup[d]);

不幸的是,这一直在抛出一个:

"export 'nest' (imported as 'd3') was not found in 'd3'

经过大量搜索,我发现在 d3 的 v4 中,我使用的 nest 被 group 替换了。现在我在文档中找不到任何内容,我试图通过以下方式实现类似的目的:

var lookup = d3.group(data, (d: any) => d.day)
.rollup((leaves: any) => {
return d3.sum(leaves, (d: any) => { return parseInt(d.count); }) as any;
})
.object(dateData);

但这似乎甚至无法编译。我将如何实现我想要做的事情?

最佳答案

所以你的问题是如何获得类似于下面的结果,但在 d3 v4 中。

var dateData = [
{ day: 1, count: 2 },
{ day: 1, count: 3 },
{ day: 1, count: 4 },
{ day: 2, count: 2 },
{ day: 4, count: 1 },
{ day: 5, count: 0 },
];
var lookup = d3.nest()
.key((d) => d.day)
.rollup((leaves) => d3.sum(leaves, (d) => parseInt(d.count)))
.entries(dateData);
console.log(lookup);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>


请注意,有一个非常好的 ES6 解决方案:

var dateData = [
{ day: 1, count: 2 },
{ day: 1, count: 3 },
{ day: 1, count: 4 },
{ day: 2, count: 2 },
{ day: 4, count: 1 },
{ day: 5, count: 0 },
];

// First, map it to a { [day]: [sum counts] } structure
// { "1": 9, "2": 2, "4": 1, "5": 0 }
var lookup = dateData.reduce((obj, { day, count }) => {
// || 0 means that if the value is undefined, it will use 0 instead
obj[day] = (obj[day] || 0) + parseInt(count);
return obj;
}, {});

// Secondly (if you want), map it to a the same structure as the v3 example
lookup = Object.entries(lookup)
.map(([key, values]) => ({ key, values }));

console.log(lookup);

关于angular - d3 - 使用 nest/group 创建查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63850172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com