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

最后都变了- 提交于 2020-06-22 12:01:45

问题


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.


回答1:


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();



回答2:


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.




回答3:


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 :)



来源:https://stackoverflow.com/questions/37004611/how-to-update-chartjs2-option-scale-tick-max

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!