d3 tick marks on integers only

Jeff Storey picture Jeff Storey · Nov 27, 2012 · Viewed 18k times · Source

I have a d3 bar chart whose values range from 0-3. I would like the y-axis to only show integer values, which I can do by

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

However, there are still tick marks at the non-integer markings. Setting the tick format only hides those labels. I can explicitly set the number of ticks or the tick values, but what I'd like to do is to just be able to specify that tick marks only appear at integer values. Is that possible?

enter image description here

Answer

diralik picture diralik · Jun 30, 2019

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.