简体   繁体   English

如何将d3.svg.axis限制为整数标签?

[英]How to limit d3.svg.axis to integer labels?

Is there any possibility to limit the number of d3.svg.axis integer labels displayed on the graph? 是否有可能限制图表上显示的d3.svg.axis整数标签的数量? Take for instance this graph. 以此图表为例。 There are only 5 sizes here: [0, 1, 2, 3, 4] . 这里只有5种尺寸: [0, 1, 2, 3, 4] However, the ticks are also displayed for .5, 1.5, 2.5 and 3.5 . 但是,刻度也显示为.5, 1.5, 2.53.5

在此输入图像描述

You should be able to use d3.format instead of writing your own format function for this. 您应该能够使用d3.format而不是d3.format编写自己的格式函数。

d3.svg.axis()
    .tickFormat(d3.format("d"));

You can also use tickFormat on your scale which the axis will automatically use by default. 您也可以在您的比例尺上使用tickFormat ,默认情况下轴将自动使用。

I've realised that it is enough to hide these values, rather than to completely exclude. 我意识到隐藏这些值就足够了,而不是完全排除。 This can be done using the tickFormat (https://github.com/mbostock/d3/wiki/Formatting#wiki-d3_format) as such: 这可以使用tickFormat (https://github.com/mbostock/d3/wiki/Formatting#wiki-d3_format)完成,如下所示:

d3.svg.axis()
    .tickFormat(function(e){
        if(Math.floor(e) != e)
        {
            return;
        }

        return e;
    });

The use of d3.format("d") as tickFormat might not work in all scenarios ( see this bug ). 使用d3.format("d")作为tickFormat可能不适用于所有场景( 请参阅此错误 )。 On Windows Phone devices (and probably others) imprecise calculations may lead to situations where ticks are not correctly detected as integer numbers, ie a tick of "3" may be internally stored as 2.9999999999997 which for d3.format("d") is not an integer number. 在Windows Phone设备(可能还有其他设备)上,不精确的计算可能会导致滴答声未被正确检测为整数,即刻度“3”可能在内部存储为2.9999999999997,对于d3.format("d")不是整数。

As a result the axis is not displayed at all. 结果,轴根本不显示。 This behaviour especially becomes apparent in tick ranges up to 10. 在最多10个刻度范围内,此行为尤其明显。

One possible solution is to tolerate the machine error by specifying an epsilon value. 一种可能的解决方案是通过指定epsilon值来容忍机器错误。 The values do not have to be exact integers this way, but may differ from the next integer up to the epsilon range (which should be way lower than your data error): 这些值不一定是精确整数,但可能与下一个整数到epsilon范围(应该低于数据错误)不同:

var epsilon = Math.pow(10,-7);

var axis = d3.svg.axis().tickFormat(function(d) {
    if (((d - Math.floor(d)) > epsilon) && ((Math.ceil(d) -d) > epsilon))
        return;
    return d;
}

Another solution, which is also mentioned in other threads, is to specify a fixed tick count and then round the ticks (which now should be "almost" integer) to the nearest integer. 另一个解决方案,也在其他线程中提到,是指定一个固定的滴答计数,然后将滴答(现在应该是“几乎”整数)四舍五入到最接近的整数。 You need to know the maximum value of your data for this to work: 您需要知道数据的最大值才能使其正常工作:

var axis = d3.svg.axis().ticks(dataMax).tickFormat(d3.format(".0f"))

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

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