[Chartjs]-Chart.js – Setting max Y axis value and keeping steps correct

6👍

Figured it out. Instead of supplying the max value on the Y Axis as I have been, I instead implemented the afterBuildTicks callback and updated the ticks to have the correct increments.

yAxes: [{
  afterBuildTicks: function(scale) {
  scale.ticks = updateChartTicks(scale);
    return;
  },
  beforeUpdate: function(oScale) {
    return;
  },
  ticks: {  
    beginAtZero:true,
    // max:plugin.settings.maxDataValue,
    maxTicksLimit: 10
  }
}] 

my updateChartTicks function loops over the existing ticks and determines the correct increment amount between the ticks. Then I use that value to add my final “tick” which will always be greater than the largest data in the dataset.

var updateChartTicks = function(scale) {
  var incrementAmount = 0;
  var previousAmount = 0;
  var newTicks = [];
  newTicks = scale.ticks;
  for (x=0;x<newTicks.length;x++) {
    incrementAmount = (previousAmount - newTicks[x]);
    previousAmount = newTicks[x];   
  }
  if (newTicks.length > 2) {
    if (newTicks[0] - newTicks[1] != incrementAmount) {
      newTicks[0] = newTicks[1] + incrementAmount;                  
    }
  }         
  return newTicks;          
};

16👍

I too had the same problem. You needn’t write any special function for determining the max value in the Yaxes. Use ‘suggestedMax’ setting. Instead for setting ‘max’ as maximum value in your graph, set suggestMax as the maximum value in your graph. This never works if you have set ‘stepsize’.

options: {
 scales: {
  yAxes: [{
    ticks: {
     suggestedMax: maxvalue+20
     }
   }]
  }
}

20 is added, so that the tooltip on max value will be clearly visible.

For more info, refer http://www.chartjs.org/docs/latest/axes/cartesian/linear.html#axis-range-settings

Leave a comment