Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using Chart.js 2.6. I have a chart to which I've added custom pagination to step through the dataset, as it is quite large. My pagination and everything works great, I simply grab the next chunk of data in my set and update the chart.config.data with the new data object, and then call .update() on the chart. However, in order to make the chart make sense, I needed to keep the left (Y-axis) scale the same when the user is paginating through. Normally Chart.js would rebuild it based on the data in the chart, but I want it to always reflect the same values.

I've set the max value on the yAxes object of the chart to the maximum value in my data set. I've also set the beginAtZero option to true, and the maxTicksLimit to 10. However, even though my Yaxis does stay the same, it doesn't always look that great (see below screenshot). In this example, my max is set to 21,000 in the chart. Does anyone have any suggestions as to how I can either provide a better max (rounding up to next 5,000, 500, 100, etc based on the value) or some way to get it to create the Y axis without crunching the top number the way it does now?

enter image description here

Here is the function I currently use to determining the max data value to set as the max value in the Yaxes object in the chart. the plugin.settings.chartData variable represents an array of the data values used in the chart. I am trying to get it to increment correctly to the next 1000, 500, etc based on what the maxValue is, but as you can see my math is not correct. In the screenshot example, the maxValue is coming back as 20,750 and my function is rounding it up to 21,000. In this example it SHOULD round it up to the next increment which would be 25,000.

var determineMaxDataValue = function() {
    var maxValue = Math.max.apply(Math, plugin.settings.chartData);
    var step = maxValue > 1000 ? 1000 : 500;
    plugin.settings.maxDataValue = (Math.ceil(maxValue / step) * step);             
};
like image 576
Phil Avatar asked Jul 03 '17 14:07

Phil


1 Answers

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

like image 83
Vidhya Avatar answered Sep 22 '22 13:09

Vidhya