Highcharts datetime line travels backwards with unsorted data

Viewed 232

I know I should have sorted data, but I'm getting it from different API calls and there are 10 other reasons why I cannot have sorted data.

I have some unsorted data, that I need to plot in a timeseries graph.

{
    xAxis: {
        type: 'datetime'
    },
    series: [{
        data: [
            [Date.UTC(2020, 0, 1), 29.9],
            [Date.UTC(2020, 0, 2), 71.5],
            [Date.UTC(2020, 0, 6), 106.4],
            [Date.UTC(2020, 0, 3), 129.2],
            [Date.UTC(2020, 0, 5), 144.0],
            [Date.UTC(2020, 0, 8), 176.0]
        ]
    }]

}

When I use the above options for highcharts, the line travels backwards enter image description here

Is there a way I can make highcharts do the required sorting, and plot the chart correctly? I have tried dataSorting option as well, but it didn't work.

Highcharts has a dataSorting flag to sort the data, so its not completely crazy of me to expect it.

2 Answers

Are you missing the dataSorting property?

{
    xAxis: {
        type: 'datetime'
    },
    series: [{
        dataSorting: {
            enabled: true,
            sortKey: 'value'
        },
        data: [
            [Date.UTC(2020, 0, 1), 29.9],
            [Date.UTC(2020, 0, 2), 71.5],
            [Date.UTC(2020, 0, 6), 106.4],
            [Date.UTC(2020, 0, 3), 129.2],
            [Date.UTC(2020, 0, 5), 144.0],
            [Date.UTC(2020, 0, 8), 176.0]
        ]
    }]

}

Highcharts requires sorted data in ascending X order. You need to pre-sorts the data, for example:

var data = [
    [Date.UTC(2020, 0, 1), 29.9],
    [Date.UTC(2020, 0, 2), 71.5],
    [Date.UTC(2020, 0, 6), 106.4],
    [Date.UTC(2020, 0, 3), 129.2],
    [Date.UTC(2020, 0, 5), 144.0],
    [Date.UTC(2020, 0, 8), 176.0]
];

data.sort((a, b) => a[0] - b[0]);

Highcharts.chart('container', {
    ...,
    series: [{
        data
    }]
});

Live demo: http://jsfiddle.net/BlackLabel/cf8tq6a2/

Related