gpt4 book ai didi

javascript - 来自 d3.stack() 的 d3,max 给出了错误的最大值

转载 作者:行者123 更新时间:2023-11-29 10:27:54 25 4
gpt4 key购买 nike

我有堆栈条形图的以下数据。当我尝试计算 y 轴的最大值时,它给了我 100。它应该是 70。有人可以告诉我我哪里做错了吗?

片段如下

//DATA
var data = [{
category: "test1",
type1: 10,
type2: 20
},
{
category: "test2",
type1: 30,
type2: 40
}
];
var keys = ["type1", "type2"];

var yScale = d3.scaleLinear()
.range([400, 0]);

var stack = d3
.stack()
.keys(keys)
.order(d3.stackOrderNone)
.offset(d3.stackOffsetNone);

var layers = stack(data);

console.log(d3.max(layers[layers.length - 1], d => (d[0] + d[1])))

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

最佳答案

结果是正确的,您找到了 (10 + 20) 和 (30 + 70) 中的最大值,即后者,100。

堆栈用两个值表示每个数据点:

Lastly, each point is represented as an array [y0, y1] where y0 is the lower value (baseline) and y1 is the upper value (topline); the difference between y0 and y1 corresponds to the computed value for this point. (docs)

根据您的输入,第一个类别具有您的 [0,10] 和 [10,30] 类型的数据点 - 第二个点的基线等于第一个点的顶线(基线 + 值)。第二类包含类型 [0,30] 和 [30,70] 的数据点。

在您的 max 函数中,您要添加 d[0]d[1],这会将上面两个元素数组中的每一个都减少为一个总和:

// for each item in the array layers[layers.length-1], find the max of d[0] + d[1]
d3.max(layers[layers.length - 1], d => (d[0] + d[1]))

这将为您提供 100,因为数组 layers[layers.length-1](代表第二类的部分)是:

[
[ 0 , 30 ],
[ 30 , 70 ]
]

关于javascript - 来自 d3.stack() 的 d3,max 给出了错误的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54010805/

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