Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 tick marks on integers only

Tags:

axis

d3.js

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

like image 728
Jeff Storey Avatar asked Nov 27 '12 03:11

Jeff Storey


1 Answers

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.

like image 59
diralik Avatar answered Sep 22 '22 07:09

diralik