javascript - 如何在 d3 图表中强制使用特定数量的 y 轴刻度?

标签 javascript d3.js

我有一个 d3(3.5 版)多线图,我试图在 y 轴上有 5 个刻度。

这是生成 y 轴的代码,带有刻度数:

enter image description here

问题是我输入的任何刻度值,在 3 到 6 之间,都会给出相同的以下结果(刻度比我想要的要少):

enter image description here

当我输入 7 个刻度值时,它会给出以下结果(比我想要的刻度数太多):

enter image description here

如何强制图表在 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/

相关文章:

javascript - 使用 jquery/Angularjs 清除浏览器缓存

javascript - HTML 图像幻灯片显示空白屏幕

d3.js - d3 中的自定义比例

javascript - Owl Carousel - 自动高度移动问题

javascript - 我觉得大多数用 jest 和 enzyme 进行的组件测试都是毫无值(value)的,我错了吗?

javascript - 如何使用 NodeJS 计算 UPS 运费?

javascript - d3 在给定半径内为气泡图设置动画

d3.js - 条形图上的 D3 渐变填充 - 带色标

jquery - 将 AngularJS/AngularUI 与 d3.js 和 DOM 效果结合使用

javascript - 使雷达图的轴以值(value)的存在为条件