Search code examples
javascripthighcharts

How do I redraw a series on HighCharts?


I am attempting to redraw data on highcharts. I use this code to initialise the chart.

    Highcharts.chart('container', {
chart: {
            events: {
                click: function(event) {
                    alert (
                    'x: '+ Highcharts.dateFormat('%Y-%m-%d', event.xAxis[0].value) +', ' +
                    'y: '+ event.yAxis[0].value
                    );
                }
            }
        },

        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
        yAxis: {
            title: {
                text: 'Amount'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },

        plotOptions: {
        series: {
            cursor: 'pointer',
            point: {
                events: {
                    click: function() {
                        alert ('Category: '+ this.category +', value: '+ this.y);
                    }
                }
            }
        }
        },
        series: [{
            name: 'Expected',
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        }, {
            name: 'Received',
            data: [1.0, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
        }],
});

Using a HTML button, I call the following

Highcharts.chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );

It gives the following error

"Uncaught TypeError: Cannot read property '0' of undefined"

Is it possible to update the chart this way?


Solution

  • You can refer to the chart by globar variable Highcharts in this way:

    Highcharts.charts[0].series[0].setData([...] );
    

    Or store the chart in a variable:

    var chart = Highcharts.chart('container', {...});
    
    chart.series[0].setData([...]);
    

    Please note that you can manage the redrawing by a parameter of setData method.


    Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4902/

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