Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flot: how to style numbers within bar-charts?

I'm using FlotCharts and it's plugin flot.barnumbers (Demo) to display charts.

I need to display the numbers within the bar, it works. Unfortunately I've no idea how to style the numbers and cannot find anything in the Docs or via Google.

I'd like to use something like (apparently not possible):

bars: {
    numbers: {
        numberFormatter: function(v, bar) {
            return '<div class="pimp-my-number-class">'+ v +'</div>';               
        }
    }
}

Flot barchart, current and goal

Does anyone have an idea, how to fix this problem?

Thank's in advance!

like image 626
Mr. B. Avatar asked Mar 23 '23 14:03

Mr. B.


1 Answers

One of the nicest things about flot is that it provides the basics and then gets out of your way. Here's a quick code example where I've implemented this myself (ie no plugins). It's short and sweet and you have complete control over appearance.

$(function() {

    dsHook = function(plot, canvascontext, series){
        for (var i = 0; i < series.data.length; i++){ // loop the series
           var offset = plot.offset(); // offset of canvas to body
           var dP = series.data[i]; // our data point
           var pos = plot.p2c({x: dP[0], y: dP[1]}); // position of point           
           var barWidth = plot.p2c({x: dP[0]+series.bars.barWidth, y: dP[1]}).left - pos.left; // calc width of bar
           pos.left += offset.left; pos.top += offset.top; //adjust position for offset
           var aDiv = $('<div></div>').css({'width':barWidth, 'background-color':'green','color':'white','text-align':'center','position':'absolute','left': pos.left,'top':pos.top}).text(dP[1]).appendTo("body"); // add an absolute div with the number
        }
    }

    var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];

    somePlot = $.plot("#placeholder", [{
            data: d2,
            bars: { show: true }
        }],
        { hooks: { drawSeries: [dsHook] } }
    );
});

enter image description here

like image 153
Mark Avatar answered Apr 07 '23 18:04

Mark