Search code examples
javascriptjqueryarraysflot

Cannot plot 2 separate graphs using FlotJs


Im trying to plot 2 separate graphs (actually it will be 9 but for now there are only 2) using flotJS, somehow the data mixes and plots the same mixed data on both graphs

Here is my JS code:

var graphData1, graphData2, graphData3 = [];
var graphBuffer = 1000;
var xmin = 0;
var xmax = 5;

var options = {
    xaxes: [
        {position: 'bottom', autoScale: 'none', min: 0, max: 5}
    ],
    yaxes: [
        {position: 'left', autoScale: 'none', min: -1.5, max: 1.5}
    ],
    zoom: {interactive: true},
    pan: {interactive: true}
};


function deleteGraph() {
    graphData1 = graphData2 = graphData3 = [];

    $.plot("#graph1", [{graphData1}], options);
    $.plot("#graph2", [{graphData2}], options);
    //$.plot("#graph3", [{graphData3}], options);
}

function updateGraph(data) {

    var datatmp = data.data;

    // Formatea y Almacena datos a graficar
    datatmp.forEach(function (sample) {
        graphData1.push([parseFloat(sample.timestamp.toFixed(4)), parseFloat(sample.sensor1.toFixed(4))]);
        //graphData2.push([parseFloat(sample.timestamp.toFixed(4)), parseFloat(sample.sensor2.toFixed(4))]);
    });

    $.plot("#graph1", [graphData1], options);
    $.plot("#graph2", [graphData2], options);

}

and with this code the output is:

graph result 1

As you can see its plotting the same information on both graphs even when //graphData2.push([parseFloat(sample.timestamp.toFixed(4)), parseFloat(sample.sensor2.toFixed(4))]); is commented

However if i remove the comment the result is this:

graph result 2

As you can see its mixing the data and plotting the same mixed data on both graphs

How can i plot different data on different graphs?

Thanks for your help...


Solution

  • You are setting graphData1 = graphData2 so they are the same array. Then you push all your data points into that one array which is shown in both charts.

    Replace

    var graphData1, graphData2, graphData3 = [];
    
    // and
    
    function deleteGraph() {
        graphData1 = graphData2 = graphData3 = [];
    

    with

    var graphData1 = [], graphData2 = [], graphData3 = [];
    
    // and
    
    function deleteGraph() {
        graphData1 = [];
        graphData2 = [];
        graphData3 = [];