Chart.js - Setting max Y axis value and keeping steps correct

▼魔方 西西 提交于 2019-12-04 18:38:48

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

Phil

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;          
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!