A.Alshaikhli
A.Alshaikhli

Reputation: 437

Chart.js automatic chosen scale value

I am using automatic scale starting value. It will generate and chose min and max number in y axis automatically. Now i am facing problem, The scale start exactly from the min number and will be finish exactly from the max number. Can i set the scale to start before the min number like 2% of the value? This is my chart: enter image description here

I just want to notice that i have random values, so i can not adjust the scale to start and end certain values! Thanks

Upvotes: 4

Views: 19634

Answers (2)

GemsFord
GemsFord

Reputation: 29

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.

Upvotes: 1

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

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>

Upvotes: 9

Related Questions