如何更新chartjs2选项(scale.tick.max)

时间:2016-05-03 12:47:35

标签: chart.js

我有一个带有此选项的条形图

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

现在我更改了我唯一的数据集

的值
      barChartData.datasets[0].data = newData;

并更新图表

      window.myBar.update();

我怎样才能更新yAxes的最大比例?

我必须使用最大比例,所以我不能使用suggestMax。

3 个答案:

答案 0 :(得分:6)

自己找到了解决方案。

更改图表的任何选项:

myBar.config.options

在我的情况下

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

之后你必须打电话

window.myBar.update();

答案 1 :(得分:1)

这是我的折线图解决方案。

您可以使用“ beforeFit ”回调函数,该函数可在文档http://www.chartjs.org/docs/latest/axes/

中找到
  1. scale.chart.config.data.datasets 中,您拥有图表数据集
  2. 您必须设置 scale.options.ticks.max

示例:

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
          }
        }

希望我能对您有所帮助。

答案 2 :(得分:0)

链接https://www.chartjs.org/docs/latest/developers/updates.html包含最新信息。 keey是识别图表对象是什么。 :) 我努力了半天阅读各种页面,直到我找到正确的方式

  1. 使用baseChartDirective直接访问图表 - > this.chart
  2. 要更新秤,请执行以下操作:
  3.  var barChartOptions =  {
          legend: { display: true },
          scales: { yAxes: [{ id: 'yaxis', type: 'linear', position: 'left', ticks: { min: 0, max: maxScale } }]}  };  
     this.chart.chart.options = barChartOptions;
    
    1. 然后更新图表:
    2.   

      this.chart.chart.update();

      你几乎可以更新所有内容。只需要了解图表对象在此页面中的含义:https://www.chartjs.org/docs/latest/developers/updates.html :)