Search code examples
javascriptlinechartanychart

How do I make a line chart not interrupt the line when values are missing?


We use AnyChart to display energy consumption data in a line chart. Here, the time of acquisition is assigned to the corresponding value. Now, if several of these series are to be displayed in one chart, I am faced with the challenge that the timestamps in the series do not always coincide, since the data is recorded at different intervals and the time of the first interval is not always the same.

For testing purposes, I have therefore created the following code that simulates the situation. At the beginning there are two rows of data sets in the same format as they are provided by the software. I transform them into ordinary JavaScript objects whereby the serialization of the timestamp is converted into a Date object. In the next step I create a line chart with these series and set DateTime as scale type.

function reviveTimestamps(key, value) {
    // Turns the serialized json timestamps into Date objects

    var a;

    if (typeof (value) === 'string') {
        a = /\/Date\((\d*)\+(\d{4})\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

let seriesOneJson = "[\
        [\"\/Date(1627544197228+0200)\/\", 10000],\
        [\"\/Date(1627545097228+0200)\/\", 12000],\
        [\"\/Date(1627545997228+0200)\/\", 18000],\
        [\"\/Date(1627546897228+0200)\/\", 11000],\
        [\"\/Date(1627547797228+0200)\/\", 9000]\
    ]";

let seriesTwoJson = "[\
        [\"\/Date(1627544197228+0200)\/\", 8000],\
        [\"\/Date(1627545097228+0200)\/\", 10000],\
        [\"\/Date(1627545197228+0200)\/\", 11000],\
        [\"\/Date(1627545897228+0200)\/\", 16000],\
        [\"\/Date(1627547797228+0200)\/\", 8000]\
    ]";

let seriesOneData = JSON.parse(seriesOneJson, reviveTimestamps);
let seriesTwoData = JSON.parse(seriesTwoJson, reviveTimestamps);

chart = anychart.line();
chart.xScale(anychart.scales.dateTime());

let series1 = chart.line(seriesOneData);
let series2 = chart.line(seriesTwoData)

chart.container("container");
chart.draw();

So far so good, I get a chart, but the problems with the different timestamps show up here. Where there are no values for a series, the line is interrupted. In situations with eight series of 80 records each, this leads to none of the lines being displayed.Screenshot of a chart with interrupted lines

My question is this: Is there any way to continue the lines to the next known point, even if a value is missing?


Solution

  • For both series, you should enable connectMissingPoints() settings. Like this:

    let series1 = chart.line(seriesOneData);
    series1.connectMissingPoints(true);
    let series2 = chart.line(seriesTwoData)
    series2.connectMissingPoints(true);