d3 tick marks on integers only

只谈情不闲聊 提交于 2019-11-27 14:58:48

You could add .ticks(4) and .tickSubdivide(0) as I've done below:

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

You can programatically set the number of ticks to data.length - 1 (this solves the issue you were having for small numbers of ticks as well)

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

The proper solution is to retrieve ticks using .ticks() method, filter them to keep only integers and pass them to .tickValues():

const yAxisTicks = yScale.ticks()
    .filter(tick => Number.isInteger(tick));
const yAxis = d3.axisLeft(yScale)
    .tickValues(yAxisTicks)
    .tickFormat(d3.format('d'));

For completeness here is explanation why other solutions are bad:

@BoomShakalaka solution uses .tickSubdivide() method, which no longer exists.

@cssndrx and @kris solutions force you to specify number of ticks, so it will not work in generic case.

Used this TIP to make this work on dynamic charts (1 or more charts on page)

That did the trick. I changed to be Math.min(maxHeight+1,yAxis.ticks()) so if the graph height is less than the number of ticks, it reduces the number of ticks. – Jeff Storey Nov 28 '12 at 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)) 

From all listed solutions, I haven't been able to get rid off tick marks.

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

remove labels but not the ticks.

So I propose to apply a threshold on ticks(). If less than 4 then it is set to the limit itself (0,1,2,3). Is done with:

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

});

A jsfiddle is available from https://jsfiddle.net/PBrockmann/k7qnw3oj/

Let me know if there is a simpler solution. Regards

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!