Ashley McKemie
Ashley McKemie

Reputation: 179

D3 - Show only middle and last tick marks on axis

I've created a line graph, where I want to display only the middle tick mark and the last tick mark. Right now I use .tickFormat to automatically generate the ticks and data for the labels (I'd prefer to use this data if possible, since it generates well rounded numbers). The code below worked initially, but once the data changes (as it will on a weekly basis), I guess the number of tick marks changes, causing it to display different tick marks. I'm using this same code on 3 different line graphs (all the same, except they use different data sets), and the ticks display differently for each.

What would be best is if I could figure out how many tick marks are generated by the function, then base what ticks to display on that. I'm not sure that is possible, though. If not, is there a way that I can achieve this?

Note: records is the array containing the x axis values. It's always a length of 5.

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickSize(0)
    .tickFormat(function(d, i, test) {
        var rounded = (Math.round((d / 1000000) * 10) / 10).toFixed(1);
        return i == records.length + 1 || (rounded == min || rounded == (parseFloat(min) + 0.1)) ? rounded + "M" : "";
    });

Thanks!

Upvotes: 3

Views: 2751

Answers (1)

Ashley McKemie
Ashley McKemie

Reputation: 179

So, this is what I ended up doing that worked, with the help of Lars' guidance:

var yAxisTicks = records;
yAxisTicks[yAxisTicks.length - 1] = d3.max(records) + 1000;
var yAxis = d3.svg.axis()
  .tickValues(yAxisTicks)
  .scale(y)
  .orient("left")
  .tickSize(0)
  .tickFormat(function(d, i){
    var rounded = (Math.round((d/10000) * 10) / 10).toFixed(1);
    return i == 0 || i == 4 ? rounded + "M": "";
  });

Ultimately, I passed an array with all the y axis values to .tickValues, then used .tickFormat to only show the first and last (as the first ended up displaying in the middle, as that's where the first data point displays)

Upvotes: 1

Related Questions