[Chartjs]-Chartjs 2.0 alpha, how to have a static scale for y-axis

2👍

Under options > yAxes

var ctx = document.getElementById("chart").getContext("2d");
var myChart = new Chart(ctx, {
    type: "line",
    data: lineChartData,
    options: {
        scales: {
            yAxes: [{
                override: {
                    stepWidth: 20,
                    start: 0,
                    steps: 10
                }
            }]
        }
    }
});

Fiddle – https://jsfiddle.net/es83ujat/

9👍

Chart.js has removed the override functionality (#1564) in v2.0 and replaced it with custom scale types and callbacks. Unfortunately, there’s no documentation on this yet, but I’ve put together something that seems to work based on the linear scale.

var UserDefinedScaleDefaults = Chart.scaleService.getScaleDefaults("linear");
var UserDefinedScale = Chart.scaleService.getScaleConstructor("linear").extend({
  buildTicks: function() {
    this.min = this.options.ticks.min;
    this.max = this.options.ticks.max;
    var stepWidth = this.options.ticks.stepWidth;

    this.ticks = [];
    for (var tickValue = this.min; tickValue <= this.max; tickValue += stepWidth) {
      this.ticks.push(tickValue);
    }

    if (this.options.position == "left" || this.options.position == "right") {
      this.ticks.reverse();
    }

    if (this.options.ticks.reverse) {
      this.ticks.reverse();
      this.start = this.max;
      this.end = this.min;
    } else {
      this.start = this.min;
      this.end = this.max;
    }

    this.zeroLineIndex = this.ticks.indexOf(0);
  }
});

Chart.scaleService.registerScaleType("user-defined", UserDefinedScale, UserDefinedScaleDefaults);

Then you can use a “user-defined” type and specify the ticks in the options:

var config = {
  type: 'line',
  data: { datasets: [{data: data}] },
  options: {
    scales: {
      xAxes: [{
        type: "linear",
        position: "bottom"
      }],
      yAxes: [{
        type: "user-defined",
        ticks: {
          min: 0,
          max: 10,
          stepWidth: 2
        }
      }]
    }
  }
};

The key function to override here is buildTicks which specifies this.min, this.max, this.start, this.end, this.zeroLineIndex, and the array of actual tick values this.ticks.

Codepen example

Leave a comment