Question

I have a line graph displaying using flot. I would like to show above each point the percentage change from the previous point. I have looked through the docs and I can't see anywhere indicating that this is possible. Is it possible?

Was it helpful?

Solution

While flot does have a point labeling plugin, I find it easier to label the points yourself. Here's a quick code snip, that'll label points with their percentage change from the last point:

var series = [{data: [[0, 1.2], [1, 3], [2, 9.2], [3, 10]]},
              {data: [[0, 6], [1, 7], [2, 13], [3, 17]]}]                  

somePlot = $.plot("#placeholder", series, {xaxis:{min:-0.2, max:3.2}});

var ctx = somePlot.getCanvas().getContext("2d");
mySeries = somePlot.getData();
var xaxis = somePlot.getXAxes()[0];
var yaxis = somePlot.getYAxes()[0];
var offset = somePlot.getPlotOffset();
ctx.font = "13px 'Segoe UI'";
ctx.fillStyle = "black";
for (var i = 0; i < mySeries.length; i++){
    for (var j = 0; j < mySeries[i].data.length; j++){
        if (j == 0) continue;
        var x = mySeries[i].data[j][0];
        var y = mySeries[i].data[j][3];
        var lastY = mySeries[i].data[j-1][4];
        var text = (((y - lastY) / lastY) * 100).toFixed(1) + '%'
        var metrics = ctx.measureText(text);
        var xPos = (xaxis.p2c(x)+offset.left) - metrics.width/2;
        var yPos = yaxis.p2c(y) + offset.top - 5;
        ctx.fillText(text, xPos, yPos);
    }
}

Fiddle here.

Outcome:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top