Search code examples
javascriptjqueryflotgraphing

Display a dataset of points, and a dataset of lines, on a single flot graph?


How can I display two data series in the same flot graph, when one series is a set of points, and one is a line?

I've seen examples of line series like this, but the complicating factor is that I'd like to display data points and a data line on the same graph.

This seems like quite a common use case - basically I want to display a scatter graph along with its line of best fit.

Currently I have

    var options = {
        series: {
            lines: {
                show: false
            },
            points: {
                show: true
            },
            lines: { 
                show: true
            }
        },
        grid: {
            hoverable: true,
        },
        yaxis: {
            min: 0,
            max: 1100000,
            font: 'Georgia'
        },
        xaxis: {
            min: 10,
            max: 480,
            font: 'Georgia'
        } 
        };
    var plot = $.plot($("#placeholder"),
    [{
        data: scatterdata,
        color: 'dodgerblue',
    }], options);
    var line = $.plot($("#placeholder"),
    [{
        data: linedata,
        color: 'black',
    }], options );

But this only displays the second set of data, not both of them.


Solution

  • You want to do something like this (specify the data sets one at a time, with options):

    $(function () {
    
        var points = [[1, 6], [2, 3], [3, 9], [4, 2], [5, 11]];
    
        var fitLine = [];
        for (var i = 0; i < 10; i += 0.5)
            fitLine.push([i, (0.9 * i) + 3.5]);
    
        $.plot($("#placeholder"), [
            {
                data: points,
                points: { show: true }
            },
            {
                data:fitLine,
                lines: { show: true }
            }
        ]);
    });
    

    Produces:

    enter image description here