Joel
Joel

Reputation: 439

Control axis tick number in D3

I am trying to use this code to create over one hundred graphs, each one being a unique graph and plotting different points. However, I need their general layouts to look the same.

When using the .ticks() function D3 seems to completely ignore whatever value I input. Every one of my graphs always comes out with a different number of ticks but I can't find a way to fix it. Is there a way to force D3 to accept my value?

This is the relevant code:

var xAxis = d3.svg.axis()  
  .orient("bottom")
  .scale(x)
  .ticks(10)
  .tickFormat(d3.format("d"))
  .tickSize(1);

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .ticks(10)
  .tickSize(1);

var yAxixObject = graph.append("g")
  .call(yAxis)
  .attr("transform", "translate("+ margin.left + "," + margin.top + ")");

var xAxisObject = graph.append("g")
  .call(xAxis)
  .attr("transform", "translate("+ margin.left + "," + (height + margin.top) + ")");

Upvotes: 2

Views: 2208

Answers (1)

Joel
Joel

Reputation: 439

From FernOfTheAndes' suggestion I ended up using the .tickValues() function. I just added a loop to create an array to input into .tickValues(). Now regardless of how different all the data is, my graphs all still have 10 ticks.

This is all the relevant code for my y axis, that is dispersed throughout my project:

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .tickSize(1);

...

var ticksNum = 10;
var yAxisTicks = [];
var yDomain = [d3.min(data, function(d){return d.Level;}), d3.max(data, function(d){return d.Level;})];
y.domain(yDomain);

...

for (var i = 0; i < ticks; i++ ){
          yAxisTicks.push((yDomain[1] - yDomain[0]) / (ticks - 1)* i + yDomain[0]);
    }

yAxis.tickValues(yAxisTicks);

...

var yAxixObject = graph.append("g")
  .call(yAxis)
  .attr("transform", "translate("+ margin.left + "," + margin.top + ")");

Upvotes: 4

Related Questions