JQuery, Flot, valuelabels, center

Plugins got you down? Just do it yourself, life it so much simpler then. This is the advantage of flot, compact code that get’s out of your way…

Here’s how I would add those labels:

// draw initial plot
// notice no categories plugin either, why?  
// Because it's easier to do it yourself...
var series = {data: [[0, 5.2], [1, 3], [2, 9.2], [3, 10]],
              lines: {show: false},
              bars: {show: true, barWidth: 0.75, align:'center'}}   
var somePlot = $.plot("#placeholder", [ series ], {
    xaxis: {
        ticks: [[0,"One"],[1,"Two"],
                [2,"Three"],[3,"Four"]]
    }
});

// after initial plot draw, then loop the data, add the labels
// I'm drawing these directly on the canvas, NO HTML DIVS!
// code is un-necessarily verbose for demonstration purposes
var ctx = somePlot.getCanvas().getContext("2d"); // get the context
var data = somePlot.getData()[0].data;  // get your series data
var xaxis = somePlot.getXAxes()[0]; // xAxis
var yaxis = somePlot.getYAxes()[0]; // yAxis
var offset = somePlot.getPlotOffset(); // plots offset
ctx.font = "16px 'Segoe UI'"; // set a pretty label font
ctx.fillStyle = "black";
for (var i = 0; i < data.length; i++){
    var text = data[i][1] + '';
    var metrics = ctx.measureText(text);
    var xPos = (xaxis.p2c(data[i][0])+offset.left) - metrics.width/2; // place it in the middle of the bar
    var yPos = yaxis.p2c(data[i][1]) + offset.top - 5; // place at top of bar, slightly up
    ctx.fillText(text, xPos, yPos);
}

Fiddle demonstration is here.

Produces:

enter image description here

Leave a Comment