4

I am using the code snippet from this stackoverflow question to label my flot data points. So far this has served me well, but now I have to label the overall values of stacked bars. There are two data series and so far I've managed to calculate the sums, but I can't seem to work out a proper positioning for my labels. I'd like to place them on top of the stacks, but pointOffset only gives me the offsets based on non-stacked bars.

This is the code I am currently using, it places the labels where the second series' data points would be, if the bars weren't stacked, which puts them somewhere in the top bars.

$.each(p.getData()[1].data, function(i, el){

    var series0 = p.getData()[0].data;
    sum = el[1] + series0[i][2]

    var o = p.pointOffset({x: el[0], y: el[1]});

    $('<div class="data-point-label">' + sum + '</div>').css( {
        position: 'absolute',
        left: o.left - 5,
        top: o.top ,
        display: 'none'
    }).appendTo(p.getPlaceholder()).fadeIn('slow');
});

Edit #1: So far I've tried using c2p/p2c, calculating the top value using the single data points' top values and finding more documentation on the stack plugin. I am afraid none of this has helped me much.

Edit #2: I've also tried the code given in this stackoverflow answer but it doesn't work for me. I suspect the author is using some label plugin ...

Community
  • 1
  • 1
Meike
  • 85
  • 5

1 Answers1

0

The solution to put the labels in the top of the bars in stack usinjg canvas is that you have to calculate the xPoint in base of the sum of the values in the complete stack.

Here is a example of code

var sumaArr = [];
for (var u = 0; u < p.getData().length; u++) {
    $.each(p.getData()[u].data, function (i, el) {
        sumaArr[i] > 0 ? sumaArr[i] = sumaArr[i] + el[1] : sumaArr[i] = el[1];
    });
}

var ctx = p.getCanvas().getContext("2d");
var data = p.getData()[p.getData().length - 1].data;
var xaxis = p.getXAxes()[0];
var yaxis = p.getYAxes()[0];
var offset = p.getPlotOffset();
ctx.font = "12px 'Segoe UI'";
ctx.fillStyle = "gray";
for (var i = 0; i < data.length; i++) {
    var text = sumaArr[i];
    var metrics = ctx.measureText(text);
    var xPos = (xaxis.p2c(data[i][0]) + offset.left) - metrics.width / 2;
    var yPos = yaxis.p2c(sumaArr[i]) + offset.top - 5;
    ctx.fillText(text, xPos, yPos);
}

The var yPos use the sume of the values that make the complete stack.