Javascript 使用 HighCharts 股票图表动态添加系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7675496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:09:45  来源:igfitidea点击:

Adding a series dynamically with HighCharts Stock Charts

javascripthighchartshighstock

提问by Naftali aka Neal

I have the following code: http://jsfiddle.net/maniator/vTjW8/

我有以下代码:http: //jsfiddle.net/maniator/vTjW8/

var createChartTemplate = function() {
    return {
        chart: new Highcharts.StockChart({

            chart: {
                renderTo: 'container'
            },
            series: []
        }),
        addSeries: function(name) {
            this.chart.addSeries({
                name: name,
                data: [],
                id: Math.floor(Math.random()*1000)
            });
        },
        addPoint: function(data, series) {
            var seriesIndex = this.seriesExists(series);
            if (!(seriesIndex === false)) {
                this.chart.series[seriesIndex].addPoint(data, false);
            }
            this.chart.redraw();
        },
        seriesExists: function(series) {
            var seriesIndex = false;
            $.each(this.chart.series, function(index, item) {
                if ($.trim(item.name) == $.trim(series)) {
                    seriesIndex = index;
                    return false;
                }
            });
            return seriesIndex;
        }
    }
}
$(function() {
    var data = usdeur.splice(0, 700);
    var chart = createChartTemplate();
    chart.addSeries("New Series");
    for (var i = 0; i < data.length; i++) {
        chart.addPoint(data[i], "New Series");
    }

});

It has the following error in the console:

它在控制台中有以下错误:

Uncaught TypeError: Cannot read property 'options' of undefined

未捕获的类型错误:无法读取未定义的属性“选项”

This code works fine if it is a normal highchart, but for some reason it does not work with a HighStock chart.

如果它是普通的 highchart,此代码工作正常,但由于某种原因,它不适用于 HighStock 图表。

How can I make it so that it works with the chart type that I need?

我怎样才能使它适用于我需要的图表类型?



Update:

更新:

I figures out a sort of way around getting the 1st series dynamically, but then when I try to add a second series it has an error of:

我想出了一种动态获取第一个系列的方法,但是当我尝试添加第二个系列时,它有一个错误:

Uncaught TypeError: Cannot read property 'stacks' of undefined

未捕获的类型错误:无法读取未定义的属性“堆栈”

Fiddle: http://jsfiddle.net/maniator/V5WAJ/

小提琴:http: //jsfiddle.net/maniator/V5WAJ/

回答by bejonbee

You are creating the chart with an empty series, hence the error. When this line of you code runs it's initializing the Highchart immediately, before the seriesoption has been set.

您正在使用空系列创建图表,因此出现错误。当这行代码运行时,它series会在设置选项之前立即初始化 Highchart 。

var chart = createChartTemplate();

I've had better experience with Highcharts when I build the series array first, then add it to the options of the constructor in the last step.

当我首先构建系列数组时,我对 Highcharts 有更好的体验,然后在最后一步将其添加到构造函数的选项中。

Specific to your example, the usdeur.jsfile already includes an initialized array of data. You simply need to pass it along in the options array. Your jsfiddle can be simplified to this.

具体到您的示例,该usdeur.js文件已经包含一个初始化的数据数组。您只需要在选项数组中传递它。您的 jsfiddle 可以简化为这个

$(function() {
    var chart = new Highcharts.StockChart({
        chart: {
            renderTo: 'container'
        },
        series: [{
            name: 'New Series',
            data: usdeur
        }]
    });
});

回答by unexplored

I found one workaround. My use case was to plot values over time, so first value that I was adding to the chart was a pair of valid time stamp with a nullfor data:

我找到了一种解决方法。我的用例是随时间绘制值,因此我添加到图表中的第一个值是一对带有null数据的有效时间戳:

series : [{
    name : 'Random data',
    data : (function() {
        var data = [], time = (new Date()).getTime();
        data.push([time, null]);                
        return data;
    })()
}]

Then whenever new values had to be plotted just added them simply as:

然后,每当必须绘制新值时,只需将它们简单地添加为:

var value = rawData['My Data Set']
var plot  = [new Date().getTime(), value]
mychart.series[0].addPoint(plot, true, false)

This can be tested here, just replace the original definition of the serieswith the one from here.

这可以在此处进行测试,只需将 的原始定义替换为此处的定义即可series

回答by kcvikander

From the HighStock API Reference on addSeries:

来自 addSeries 上的 HighStock API 参考:

In a StockChart with the navigator enabled, the base series can't be added dynamically.

在启用导航器的 StockChart 中,不能动态添加基本系列。

That is to say, if you're using the Navigator, you have to start with at least one series. According to the same API Reference, the Navigator displays by default.

也就是说,如果你使用导航器,你必须至少从一个系列开始。根据相同的 API 参考,导航器默认显示。

回答by ejectamenta

I have found that you can use the following code in the dynamically called function to get round the highstock option.series[0] = null problem

我发现您可以在动态调用的函数中使用以下代码来解决 highstock option.series[0] = null 问题

options.series= [{data:[]}];

// you can now add the dynamic data, eg

options.series[0].data.push([time, val]);

回答by Muatik

I achieved adding time series dynamically as follows:

我实现了动态添加时间序列如下:

the HTML part, nothing fancy is here:

HTML 部分,这里没什么特别的:

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

and javascript part:

和 javascript 部分:

  $(function () {

  var chart = Highcharts.chart('container', {
    chart: {
      type: 'line'
    },
    title: {
      text: ''
    },
    subtitle: {
      text: ''
    },
    yAxis: {
      title: {
        text: 'Values'
      }
    },
    plotOptions: {
      line: {
        dataLabels: {
          enabled: true
        },
        enableMouseTracking: true
      }
    },
    series: [{
      name: 'A',
      color: "#ea825f",
      data: []
      // 
    },{
      name: 'B',
      color: "#2a82ff",
      data: []
      // data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }]
  });

  var data1 = [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6];
  var data2 = [4.0, 11.9, 6.5, 12.5, 11.4, 15.5, 29.2, 24.5, 21.3, 15.3, 14.9, 8.6]

  function add_timeseries(data, chart, series_index) {
    $.map(data, function(i){
        chart.series[series_index].addPoint(i, true, false)
    })
  }
  add_timeseries(data1, chart, 0)
  add_timeseries(data2, chart, 1)
});

add_timeseries()function does the actual job, it fills the time series slot with given data

add_timeseries()函数完成实际工作,它用给定的数据填充时间序列槽

https://jsfiddle.net/muatik2/vxym5xx5/6/

https://jsfiddle.net/muatik2/vxym5xx5/6/

回答by backslashN

You can create the template first and add the series later. But once you have added at least one series, you cannot remove the highcharts-navigator-series(auto-generated) from a HighStockchart. If you want to remove all the series, you can use below code:

您可以先创建模板,然后再添加系列。但是一旦您添加了至少一个系列,您就无法highcharts-navigator-seriesHighStock图表中删除(自动生成的)。如果要删除所有系列,可以使用以下代码:

while (chart.series.length > 0) {
    if (chart.series[0].options.id == 'highcharts-navigator-series') {
        break;
    }
    chart.series[0].remove(true);
}

This will remove all the series except the navigator series. You can then safely add new series to your chart.

这将删除除导航器系列之外的所有系列。然后,您可以安全地将新系列添加到图表中。