javascript d3.js 如何在使用 nice() 时获得 scale 域的最小值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26680926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
d3.js how to get minimum value of scale's domain when using nice()
提问by Jordan
I have a scatter plot where I am trying to plot a reference point that should appear directly on the x-axis, but I am creating the y-axis like so:
我有一个散点图,我试图在其中绘制一个应该直接出现在 x 轴上的参考点,但我正在创建 y 轴,如下所示:
// give ourselves some space
yMin = yMin * 0.9;
yMax = yMax * 1.1;
// set up y
var yValue = function (d) {
return d.price;
},
yScale = d3.scale.linear()
.domain([yMin, yMax])
.range([height, 0])
.nice(),
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
The issue is that I want to plot a reference point directly on the x-axis. If I don't use .nice(), I can easily plot the reference point like so:
问题是我想直接在 x 轴上绘制一个参考点。如果我不使用 .nice(),我可以轻松地绘制参考点,如下所示:
var reference = svg.append('g').attr("class", "grid-reference");
reference.append("circle").attr("id", "some-reference-value")
.attr("class", "dot")
.attr("r", 9)
.attr("cx", xScale(someReferenceValue))
.attr("cy", yScale(yMin))
.style("fill", "grey")
.style("opacity", 1);
but I can't seem to figure out how to do this when using .nice(). Is there another way I could go about this such as somehow getting the y-coordinate of the x-axis line?
但我似乎无法弄清楚在使用 .nice() 时如何做到这一点。有没有另一种方法可以解决这个问题,例如以某种方式获取 x 轴线的 y 坐标?
I started digging through the d3 code to see how I could calculate the nice value and I understand the code, but it seems wasteful to calculate the value again not to mention the unnecessary maintenance of duplicate code - especially considering I also have reference points I will need to plot along the y-axis and I am using a logarithmic scale for my x-axis (the logarithmic nice() function is different from the linear nice() function so this would mean additional duplicate code and unnecessary maintenance).
我开始挖掘 d3 代码以了解如何计算 nice 值并且我理解了代码,但是再次计算该值似乎很浪费,更不用说对重复代码进行不必要的维护了 - 特别是考虑到我也有参考点我会需要沿 y 轴绘制,我的 x 轴使用对数刻度(对数 nice() 函数与线性 nice() 函数不同,因此这意味着额外的重复代码和不必要的维护)。
Ideas?
想法?
回答by Lars Kotthoff
You can simply query the scale for its domain after .nice()
and then get the minimum value of that:
您可以简单地查询其域的比例.nice()
,然后获取其最小值:
var yMin = yScale.domain()[0];