简体   繁体   English

将 D3 从 v4 升级到 v6 后,轴移动到图形中心

[英]Axis moving to center of graph after upgrading D3 from v4 to v6

I have just upgraded my d3 version from v4 to v6 and had made no changes to the way I draw my graphs yet.我刚刚将我的 d3 版本从 v4 升级到 v6,并且还没有改变我绘制图表的方式。 Before when the minimum and maximum data values were all 0 the x-axis at y = 0 would be set on the bottom of the chart which is what I am trying to keep.在最小和最大数据值都为 0 之前,y = 0 处的 x 轴将设置在图表的底部,这是我想要保留的。 Now it looks like d3 moves it into the center of the chart for some reason.现在看起来 d3 出于某种原因将其移动到图表的中心。 v4 on left and v5 & v6 on right:左侧为 v4,右侧为 v5 和 v6: 在此处输入图像描述 在此处输入图像描述 I also noticed this change when moving from v4 to v5 but on the changelog I cant find anything that talks about the yScale changes which is what i believe is causing it.从 v4 迁移到 v5 时,我也注意到了这种变化,但在更新日志中我找不到任何关于 yScale 更改的内容,我认为这是导致它的原因。 This only happens when the yScale.domain is set to ([0,0]) but when there is positive or negative value it seats correctly at the bottom or top of the chart like so.这仅在 yScale.domain 设置为 ([0,0]) 时发生,但是当存在正值或负值时,它会像这样正确地位于图表的底部或顶部。

在此处输入图像描述

I have searched all over and tried to modify the domains but no luck.我已经到处搜索并尝试修改域但没有运气。 Does anyone know what had changed or possibly another idea of what to try next?有谁知道发生了什么变化,或者可能对接下来要尝试什么有另一个想法? Thank you.谢谢你。

That was a deliberate decision (that user, mbostock , is D3 creator): https://github.com/d3/d3-scale/issues/117这是一个深思熟虑的决定(用户mbostock是 D3 创建者): https://github.com/d3/d3-scale/issues/117

What you could do as a quick fix is checking the scale's domain values beforehand, if they are the same then set the returned value to the start of the range:作为快速修复,您可以做的是事先检查刻度的域值,如果它们相同,则将返回的值设置为范围的开头:

 const scale = d3.scaleLinear().domain([0, 0]).range([0, 10]); const value = 0 //this is the current expected result console.log(scale(value)); //check the domain values first console.log(scale.domain()[0] === scale.domain()[1]? scale.range()[0]: scale(value))
 <script src="https://d3js.org/d3.v6.min.js"></script>

Because you have the axis depending on the scale, a better solution would be setting a minimum value for the scale's end which is not zero.因为您的轴取决于比例,所以更好的解决方案是为比例的末端设置一个不为零的最小值。 For instance:例如:

scale.domain([0, d3.max(yourData) || minValue]);

Which will evaluate to your minValue if d3.max(yourData) is zero.如果d3.max(yourData)为零,它将评估您的minValue

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

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