[Chartjs]-Chart.js – How does it calculate Y-Axis on bar chart?

1πŸ‘

βœ…

What I ended up doing is writing a function that will take the max value in my full dataset and divide it by the value I supply to the Y Axis maxTicksLimit attribute. Then I run this value through complex if/else if condition that looks something like the following.

Then I use what is returned as step and supply that to the chart as the Y axis stepSize attribute. Looks to work pretty good. If anyone has a better solution PLEASE let me know as this one is based on my hard coded calculations and I would prefer a more dynamic approach.

var determineStepSize = function(maxDatasetValue) {
     var maxStepTemp = Math.ceil(maxDatasetValue / maxYAxisTicks);
     // Determine what the step should be based on the maxStepTemp value
     if (maxStepTemp > 4000000) step = 8000000;
     else if (maxStepTemp > 2000000) step = 4000000;
     else if (maxStepTemp > 1000000) step = 2000000;
     else if (maxStepTemp > 500000) step = 1000000;
     else if (maxStepTemp > 250000) step = 500000;
     else if (maxStepTemp > 100000) step = 200000;          
     else if (maxStepTemp > 50000) step = 100000;
     else if (maxStepTemp > 25000) step = 50000;
     else if (maxStepTemp > 10000) step = 20000;
     else if (maxStepTemp > 5000) step = 10000;
     else if (maxStepTemp > 2500) step = 5000;
     else if (maxStepTemp > 1000) step = 2000;
     else if (maxStepTemp > 500) step = 1000;
     else step = 500;                   
     return step;
};

0πŸ‘

I found in the similar situation as you. I created a more generic approach by using a stepSize and max attributes.

// StepSize Function
stepSize = (maxValue) => {
  return parseInt((this.maxValue / (numberOfRowsYouWant - 1)).toFixed(0));
} 

// In Scale Options
scales: {
  yAxes: [{
    display: true,
    ticks: {
       max: this.maxValue + this.stepSize(),
       stepSize: this.stepSize(),
       display: true,
       beginAtZero: true
    }
  }]
}

Leave a comment