我有一个 d3(3.5 版)多线图,我试图在 y 轴上有 5 个刻度。
这是生成 y 轴的代码,带有刻度数:
问题是我输入的任何刻度值,在 3 到 6 之间,都会给出相同的以下结果(刻度比我想要的要少):
当我输入 7 个刻度值时,它会给出以下结果(比我想要的刻度数太多):
如何强制图表在 y 轴上具有精确的刻度数?
谢谢。
最佳答案
根据documentation (加粗我的):
A stateless method that returns approximately count representative values from the scale's input domain. If count is not specified, it defaults to 10. The returned tick values are uniformly spaced, have human-readable values (such as multiples of powers of 10), and are guaranteed to be within the extent of the input domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. The specified count is only a hint; the scale may return more or fewer values depending on the input domain.
d3
不遵守您的滴答计数的原因是您最终会得到不均匀间隔的滴答或非漂亮、非人类可读的值。
如果您真的想要 5 个刻度,则需要使用 tickValues 自行指定它们方法。我过去这样做的一种方法是使用 d3 range
方法。假设我的输入域在您的第一张图中看起来是 20 到 170,那么:
var step = 5,
min = 20,
max = 170,
stepValue = (max - min) / (step - 1),
tickValues = d3.range(min, max + stepValue, stepValue);
console.log(tickValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
关于javascript - 如何在 d3 图表中强制使用特定数量的 y 轴刻度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51497534/