Search code examples
javascriptjquerychartsinterpolationflot

How can I use a getData to pick data from only one line in a flot chart?


I was wondering if I could pick up some specific data from a multiple line chart.

As shown in this example http://people.iola.dk/olau/flot/examples/tracking.html , this program is made using two 'for' loops (i and j) and a linear interpolation. It uses a getData to read the values. Finally, the numeric values are shown directly in the label.

However, I don't want to show the numeric value of both lines, but only for one of them.

How can I do that? How can I make the computer read only the value of sin(x) and forget about cos(x)?

I attach a piece of the example code directly so you don't have to copy it.

function updateLegend() {
    updateLegendTimeout = null;

    var pos = latestPosition;

    var axes = plot.getAxes();
    if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
        pos.y < axes.yaxis.min || pos.y > axes.yaxis.max)
        return;

    var i, j, dataset = plot.getData();
    for (i = 0; i < dataset.length; ++i) {
        var series = dataset[i];

        // find the nearest points, x-wise
        for (j = 0; j < series.data.length; ++j)
            if (series.data[j][0] > pos.x)
                break;

        // now interpolate
        var y, p1 = series.data[j - 1], p2 = series.data[j];
        if (p1 == null)
            y = p2[1];
        else if (p2 == null)
            y = p1[1];
        else
            y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);

        legends.eq(i).text(series.label.replace(/=.*/, "= " + y.toFixed(2)));
    }
}

Solution

  • Just get rid of the outer i loop and use var series = dataset[0];

    function updateLegend() {
    
        updateLegendTimeout = null;
    
        var pos = latestPosition;
    
        var axes = plot.getAxes();
        if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
            pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
            return;
        }
    
        // dataset[0] is the sin series...
        var j, dataset = plot.getData();
        var series = dataset[0];
    
        // Find the nearest points, x-wise
    
        for (j = 0; j < series.data.length; ++j) {
            if (series.data[j][0] > pos.x) {
                break;
            }
        }
    

    Updated fiddle.