Reputation: 2673
New to HighCharts. I have a column chart and I want to be able to plug various subsets of my business data into the columns. For this test, my data series are:
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'}
];
In my chart, one series is defined:
series: [{
dataLabels: {
enabled: true
},
data: originalData
}]
Elsewhere on the page (outside of the chart) I have some links the user can click to check out the alternate data set. A command like chart.series[0].setData(alternateData)
changes the chart to the second data series, but then the reverse (chart.series[0].setData(originalData)
) does not change it back to the original data! Because the data is passed by reference, I guess, the first switch to alternateData
overwrites the originalData
array with the alternate data values.
I have tried cloning the data sets by assigning [...originalData]
and [...alternateData]
as the series, but it doesn't solve my problem (maybe because the array has Object values???). Is there a better way to solve this problem? In sum: how can I swap data series in my HighCharts chart, without overwriting the original data?
Upvotes: 0
Views: 1859
Reputation: 97
I had this issue as well. My solution was to remove the series that is to be updated and the create a new one:
chart.series.remove()
chart.addSeries({
data: alternateData
})
Upvotes: 1
Reputation: 39149
Yes, you are totally right. Highcharts for performance reasons mutates the original data array. You can return your data from a function to prevent mutations.
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());
Live demo: http://jsfiddle.net/BlackLabel/3Lkyhqv8/
Github thread: https://github.com/highcharts/highcharts/issues/4259
Upvotes: 2