【问题标题】:How can I change data series dynamically in HighCharts without overwriting initial series?如何在 HighCharts 中动态更改数据系列而不覆盖初始系列?
【发布时间】:2021-08-05 21:01:51
【问题描述】:

HighCharts 新手。我有一个柱形图,我希望能够将我的业务数据的各种子集插入到这些列中。对于这个测试,我的数据系列是:

const originalData = [
    {y:0.033, color:'red'},
    {y:0.025, color:'yellow'},
    {y:0.161, color:'green'},
    {y:0.116, color:'purple'},
    {y:0.665, color:'blue'}
];
const alternateData = [
    {y:0.665, color:'red'},
    {y:0.025, color:'yellow'},
    {y:0.116, color:'green'},
    {y:0.161, color:'purple'},
    {y:0.033, color:'blue'}
];

在我的图表中,定义了一个系列:

    series: [{
        dataLabels: {
            enabled: true
        },
        data: originalData
    }]

在页面的其他地方(图表之外)我有一些链接,用户可以单击以查看备用数据集。 chart.series[0].setData(alternateData) 之类的命令将图表更改为第二个数据系列,但反向 (chart.series[0].setData(originalData)) 不会将其更改回原始数据!因为数据是通过引用传递的,我猜,第一次切换到alternateData 会用备用数据值覆盖originalData 数组。

我尝试通过将[...originalData][...alternateData] 指定为系列来克隆数据集,但这并不能解决我的问题(可能是因为数组具有对象值???)。有没有更好的方法来解决这个问题? 总而言之:如何在 HighCharts 图表中交换数据系列,而不覆盖原始数据?

【问题讨论】:

    标签: javascript highcharts


    【解决方案1】:

    是的,你完全正确。出于性能原因,Highcharts 会改变原始数据数组。您可以从函数中返回数据以防止突变。

    const getOriginalData = () => [
            {y:0.033, color:'red'},
            ...
    ];
    const getAlternateData = () => [
            {y:0.665, color:'red'},
            ...
    ];
    
    const chart = Highcharts.chart('container', {
        series: [{
            data: getOriginalData()
        }]
    });
    
    // later update
    chart.series[0].setData(getAlternateData());
    // next update
    chart.series[0].setData(getOriginalData());
    

    现场演示: http://jsfiddle.net/BlackLabel/3Lkyhqv8/

    Github 线程: https://github.com/highcharts/highcharts/issues/4259

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      相关资源
      最近更新 更多