Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update chartjs2 option (scale.tick.max)

Tags:

chart.js

I have a Bar Chart with this Option

     scales: {
        yAxes: [{
          ticks: {
            display:false,
            beginAtZero:true,
            max: 1150
          }
        }]
      }

now i change the values of my only dataset

      barChartData.datasets[0].data = newData;

and update the chart

      window.myBar.update();

How can i also update the max scale of the yAxes??

I have to use a max scale so i cant use suggestedMax.

like image 815
Oachkatzl Avatar asked May 03 '16 12:05

Oachkatzl


2 Answers

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.

like image 157
Samuele Caprioli Avatar answered Oct 31 '22 02:10

Samuele Caprioli


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();
like image 23
Oachkatzl Avatar answered Oct 31 '22 00:10

Oachkatzl