Highcharts-实时更新柱形图

时间:2018-10-05 07:26:31

标签: javascript html highcharts

我试图动态更新column类型的Highcarts,但没有运气。这是column图表的演示代码:

HTML:

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

JS:

Highcharts.chart('container', {
    chart: {
        type: 'column',
    },
    title: {
        text: ''
    },
    xAxis: {
        type: 'category'
    },
    yAxis: {
        title: {
            text: ''
        },
            max: 100
    },
    legend: {
        enabled: false
    },
    exporting: {
        enabled: false
    },
    plotOptions: {
        series: {
            borderWidth: 0,
            dataLabels: {
                enabled: true,
                format: '{point.y:.1f}m/s²rms'
            }
        }
    },    
    "series": [
        {
            "name": "",
            "colorByPoint": true,
            "data": [
                {
                    "name": "",
                    "y": 30
                }
            ]
        }
    ]
});

我想动态更新y值。我试图将其添加到JS的charts部分:

Highcharts.chart('container', {
    chart: {
        type: 'column',

        // This is my new code to update Y every second
        load : function() {
          var series = this.series[0];
          setInterval(function() {
            y = Math.random();
            series.data.y([y]);
          }, 1000);
        }
        // End of my new code
    },
    title: {
        text: ''
    },
    xAxis: {
        type: 'category'
    }, 
[...]

JSFiddle: https://jsfiddle.net/af8p9yon/

有人可以告诉我如何使用Javascript存档吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

您的代码中有两个错误,没有events属性,应使用setDataupdate方法:

使用setData方法

    events: {
        load: function() {
            var series = this.series[0];
            setInterval(function() {
                y = Math.random();
                series.setData([y]);
            }, 1000);
        }
    }

使用更新方法

events: {
  load: function() {
    var series = this.series[0];
    setInterval(function() {
      y = Math.random() * 100;
      series.update({
        data: [y],
      }, true)
    }, 1000);
  }
}

实时演示:https://jsfiddle.net/BlackLabel/Louath3b/

API:

https://api.highcharts.com/class-reference/Highcharts.Series#setData

https://api.highcharts.com/class-reference/Highcharts.Series#update