Highcharts - 实时数据和不同时间间隔的选择错误

时间:2017-09-08 16:41:36

标签: javascript highcharts

我正在使用highcharts,我正在尝试开发一个可以处理实时数据的图表。

这是我的第一次尝试:

var data = [],
  chart_interval = undefined;

Highcharts.setOptions({
  global: {
    useUTC: false
  }
});

function addRandomData(dataSet, frequency, yMax, count) {
  for (var i = 1; i <= count; i++) {
    var x = new Date((new Date()).getTime() + i * frequency),
      y = Math.random() * yMax;

    dataSet.push({
      x: x,
      y: y
    });
  }

  return dataSet;
}

function addDataInterval(dataSet, frequency, yMax) {
  return setInterval(function() {
    var x = new Date(dataSet[dataSet.length - 1].x.getTime() + frequency),
      y = Math.random() * yMax;

    dataSet.push({
      x: x,
      y: y
    });
  }, frequency);
}

// Parameters: dataSet, frequency, yMax, count
addRandomData(data, 1000, 10000, 60);
//  Parameters: dataSet, frequency, yMax
addDataInterval(data, 500, 10000);

// Create the chart
Highcharts.stockChart('container', {
  chart: {
    zoomType: 'x',
    events: {
      load: function() {

        // set up the updating of the chart each second
        var series = this.series[0];
        setInterval(function() {
          series.update({
            data: data
          }, true);
        }, 1000);
      }
    }
  },

  rangeSelector: {
    buttons: [{
      count: 1,
      type: 'minute',
      text: '1M'
    }, {
      count: 5,
      type: 'minute',
      text: '5M'
    }, {
      type: 'all',
      text: 'All'
    }],
    inputEnabled: false,
    selected: 0
  },

  title: {
    text: 'Live random data'
  },

  exporting: {
    enabled: false
  },

  series: [{
    name: 'Random data',
    data: data
  }]
});
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

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

问题:如果现有数据具有不同的时间间隔,例如新生成的数据,则可自由选择的缩放不起作用。

我在某个地方犯了错误,或者这是一个错误的高图?

1 个答案:

答案 0 :(得分:2)

Highcharts希望时间值为时间戳,以毫秒为单位,而不是Date个对象:

What format does the highcharts js library accept for dates?
Highcharts X-Axis time from JS date

更改生成x值的方式,缩放会神奇地重新开始工作:

var x = (new Date()).getTime() + i * frequency,

...

var x = dataSet[dataSet.length - 1].x + frequency,

https://jsfiddle.net/74zdsvbo/