d3仅在整数上打勾

问题描述 投票:20回答:4

我有一个d3条形图,其值范围为0-3。我希望y轴只显示整数值,我可以这样做

var yAxis = d3.svg.axis().scale(y).orient("right").tickFormat(d3.format("d"));

但是,非整数标记处仍有刻度标记。设置刻度格式只会隐藏这些标签。我可以明确设置刻度数或刻度值,但我想做的是只能指定刻度线只出现在整数值。那可能吗?

d3.js axis
4个回答
17
投票

您可以添加.ticks(4)和.tickSubdivide(0),如下所示:

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("right")
    .ticks(4)
.tickFormat(d3.format("d"))
    .tickSubdivide(0);

6
投票

您可以以编程方式将刻度数设置为data.length - 1(这解决了您对少量刻度的问题)

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("right")
    .tickFormat(d3.format("d"))
    .ticks(data.length - 1)

1
投票

使用此提示使其在动态图表上工作(页面上的一个或多个图表)

这就是诀窍。我改为Math.min(maxHeight + 1,yAxis.ticks()),因此如果图形高度小于刻度数,则会减少刻度数。 - 杰夫斯托伊于2012年11月28日凌晨2点47分

  // It is either 10 or Maximum Chart height + 1 

        var graphValues = selection.data()[0].map(function(obj) {
            return obj['count'];
        }).compact();  

        Array.prototype.maxValArray = function() {
          return Math.max.apply(null, this);
        };

        var maxValue = graphValues.maxValArray();

        yAxis.ticks(Math.min(maxValue + 1, 10)) 

0
投票

从所有列出的解决方案中,我都无法摆脱刻度线。

.xAxis().ticks(4)
.tickFormat(d3.format("d"));

删除标签但不删除标记。

所以我建议在ticks()上应用一个阈值。如果小于4,则将其设置为限制本身(0,1,2,3)。完成了:

.on("preRedraw", function(chart) {
    var maxTick = chart.group().top(1)[0].value;
    if (maxTick < 4) {
      chart.xAxis().ticks(maxTick);
    } else {
      chart.xAxis().ticks(4);
    }

});

可以从https://jsfiddle.net/PBrockmann/k7qnw3oj/获得一个jsfiddle

如果有更简单的解决方案,请告诉我。问候

© www.soinside.com 2019 - 2024. All rights reserved.