0
votes

I'm trying to create an interactive and real-time graph using flot library. It's very similar to the real-time example in Flot site but with some additional options. This is a part of my code:

var bars = false;
var lines = true;
var steps = false;
var xAxisInterval = 5;
var xAxisUnit = "minute";
var plot = 0;


var dataChart = [
    {
        label : "Consumo",
        data : input1_data, //history
        threshold : {below : threshold},
        color : input1_color, //'#00B800',
        lines : {show : input1_show, fill : input1_fill}
    },
    {
        label : "Consumo Previsto",
        data : input2_data, //forecast data
        threshold : {below : threshold},
        //stack : null,
        color : input2_color,//'#66E066',
        lines : {show : input2_show, fill : input2_fill}
    }
];

var plotOptions = {
    lines:{
        show: lines,
        steps: steps
    },
    bars: {
        show: bars,
        barWidth: 0.6
    },
    yaxis:{ min:0, max: 65000 },
    xaxis: { mode : "time", tickSize : [ xAxisInterval, xAxisUnit ] },
    zoom: { interactive : gridZoom },
    pan: { interactive : gridPan },
    points: { show: showPoints },
    grid: { hoverable: gridHoverable, color: gridColor },
    legend: { backgroundColor:legendBackgroundColor, backgroundOpacity:legendBackgroundOpacity, position: legendPosition }
    };

    if (plot == 0) {
        plot = $.plot("#" + divId, dataChart, plotOptions);
    }
    else {
        jQuery.each(dataChart , function(index, value) {
            plot.setData([value.data]);
        });
        plot.setupGrid();
        plot.draw();
    }

If i only use the code line $.plot("#"+divId, dataChart, plotOptions), it works well. enter image description here

But to improve performance, instead of construt an entire new plot in every time increment, i tryed to use the code in if/else statement. But the ploted chart loss some options, like series colors and legend, and is painted with color defined in grid options (gridColor) ..., as shown in figure below.

enter image description here

Is this a bug or am I doing something wrong?

1

1 Answers

1
votes

You are replacing the all the series options with just the data piece. Also, setData replaces all the data in the chart, so I don't think calling it multiple times in a loop is correct (you'll only end up with the last series).

I usually follow this pattern to replace just the data:

var series = plot.getData();
for (var i = 0 i < dataChart.length; i++){
    series[i].data = dataChart[i].data;
}
plot.setData(series);
plot.setupGrid();
plot.draw();