[Chartjs]-How to update chartjs2 option (scale.tick.max)

13👍

found the Solution myself.

to change any options of the chart:

myBar.config.options

in my case

myBar.config.options.scales.yAxes[0].ticks.max = newValue

after this you have to call

window.myBar.update();

5👍

This is my solution for Line Chart.

You can use ‘beforeFit‘ callback function that you can find here in the docs http://www.chartjs.org/docs/latest/axes/

  1. In scale.chart.config.data.datasets you have the chart dataset
  2. You must set the scale.options.ticks.max

Example:

scales: {
        yAxes: [{
          beforeFit: function (scale) {

            // See what you can set in scale parameter
            console.log(scale)

            // Find max value in your dataset
            let maxValue = 0
            if (scale.chart.config && scale.chart.config.data && scale.chart.config.data.datasets) {
              scale.chart.config.data.datasets.forEach(dataset => {
                if (dataset && dataset.data) {
                  dataset.data.forEach(value => {
                    if (value > maxValue) {
                      maxValue = value
                    }
                  })
                }
              })
            }

            // After, set max option !!!
            scale.options.ticks.max = maxValue
          }
        }

I hope I’ve been helpful.

1👍

The link https://www.chartjs.org/docs/latest/developers/updates.html has pretty up to date information.
the keey is to recognise what the chart object is. 🙂
I struggled for half a day reading various pages until i found the right way

  1. use the baseChartDirective to access the chart directly by doing this -> this.chart
  2. To update scales do this:
 var barChartOptions =  {
      legend: { display: true },
      scales: { yAxes: [{ id: 'yaxis', type: 'linear', position: 'left', ticks: { min: 0, max: maxScale } }]}  };  
 this.chart.chart.options = barChartOptions;
  1. then update the chart:

this.chart.chart.update();

you can pretty much update everything. Just need to realise what the chart object means in this page: https://www.chartjs.org/docs/latest/developers/updates.html
🙂

Leave a comment