[Chartjs]-Chart.js automatic chosen scale value

9👍

You can use min and max property of y-axis ticks, to set a minimum (start) and maximum (end) scale value respectively.

scales: {
   yAxes: [{
      ticks: {
         min: Math.min.apply(this, data_array) - 5,
         max: Math.max.apply(this, data_array) + 5
      }
   }]
}

ᴅᴇᴍᴏ

var data_array = [20, 22, 24, 28, 30];

var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'BAR',
         data: data_array,
         backgroundColor: 'rgba(0, 119, 290, 0.5)',
         borderColor: 'rgba(0, 119, 290, 0.6)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               min: Math.min.apply(this, data_array) - 5,
               max: Math.max.apply(this, data_array) + 5,
               stepSize: 5
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

1👍

Adding to the GRUNT answer.

function round(x) { 
    return Math.ceil(x / 5) * 5; 
}

min: round(Math.min.apply(this, data_array) - 5),
max: round(Math.max.apply(this, data_array) + 5),

This will make the chart more beautiful if your stepSize is 5.

Leave a comment