Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set static value in y-axis in chart.js?

Tags:

chart.js

Click here to view the Graph figure...

like image 573
Rexie Galban Avatar asked May 26 '16 04:05

Rexie Galban


1 Answers

That would be a nice feature, but I don't think there is a direct way to do that. You could use the afterBuildTicks call back in combination with the min, max, and autoSkip options.

The Fix

The afterBuildTicks callback is passed the scale object. The scale object has an array of all the ticks to be displayed (stored in scale.ticks) so you could set your ticks in that array. Chart.js tries to make your chart look nice, so it will not show all the ticks by default. To fix this set the min and max to the lowest and highest values in your custom scale range. Also set autoSkip = false to make sure that all the ticks are displayed.

Example

jsfiddle with your example scale

jsfiddle with a smaller scale range

var ticks = [11000, 10000, 7000, 3000, 1000, 500, 100];
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
    datasets: [{
      data: [6000, 5000, 8000, 2000, 10000, 3500, 6000, 2000, 4000, 6000]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          autoSkip: false,
          min: ticks[ticks.length - 1],
          max: ticks[0]
        },
        afterBuildTicks: function(scale) {
          scale.ticks = ticks;
          return;
        },
        beforeUpdate: function(oScale) {
          return;
        }
      }]
    }
  }
});
like image 137
L Bahr Avatar answered Oct 07 '22 00:10

L Bahr