How do I specify the number of axis tick marks in d3?
d3.js, javascript, svg
Solution
You can can pass an array of ticks to an axis, and the axis will then plot ticks at the points in an array.
Here is some sample code. An axis is created that runs between 0 and 100. Tick marks are plotted at 0, 50, 60 and 100, in accordance with the 'ticks' array.
svg = d3.select("svg")
var myScale = d3.scale.linear()
.domain([0,100])
.range([0,400]);
var ticks = [0,50,60,100];
var myAxis = d3.svg.axis()
.scale(myScale)
.tickValues(ticks);
svg.append("g")
.attr("class", "axis")
.call(myAxis)
.attr("transform","translate(100,100)");
Here is an interactive example: http://tributary.io/inlet/5207532
Problem
I have created a simple bar chart in d3 and format the y-axis with '.ticks(3)', indicating I'd like to see 3 tick marks. However, depending on the data, I sometimes see 3 tick marks and sometimes see 4. Also, even when I do get 3 tick marks, the ticks are at around 1/4 up the axis label, then another at 50%, then another at 3/4. How do I force d3 to set 3 axis labels, one at the bottom, one at the middle, and one at the top?