jqPlot Bar Chart value-based colours

jqPlot is an excellent, easy to use, javascript library for generating dynamic charts. I found it very easy to create just the right type of bar-charts that I was looking for, with the exception that it does not support any method to select bar colours based on their data values. That is, suppose you want all bars less than X to be red, all less than Y to be yellow and all others to be green. There is no way to do this via option parameters. So to implement the functionality, requires hacking of the supplied jqPlot files.

First, open jquery.jqplot.js and search for $.jqplot.ColorGenerator = function(colors) { ...
In here, modify this.next = function() to this.next = function(val, max). This method is called by every plugin rendered to get the colour for each data point.

So we now need to open up the chart rendered and pass these values in. For Bar Charts, open up the jqplot.barRendered.js file and search for positiveColors.next(). You will find 4 instances of this. Change the first two to positiveColors.next(this.data[i][0], this._yaxis.max) and the last two to positiveColors.next(this.data[i][0], this._xaxis.max). Now search for negativeColors.next(). There are only two instances of this. Change the first to negativeColors.next(this.data[i][0], this._yaxis.max) and the second to negativeColors.next(this.data[i][0], this._xaxis.max).



We now have the data-point value and maximum value being passed to the ColorGenerator.next function, so we can easily modify the logic to return a color based on whatever rules we want. For example, to always return red when the value is less than 33.3%, yellow when less than 66.6% and green otherwise, you'd write something like this:


this.next = function (val, max) { 
            if(!max) return 'red';
            var p = val * 100 / max;
            if(p < 33.3) return 'red';
            if(p < 66.6) return 'yellow';
            return 'green';
        };


You could go one-step further and modify jqplot to take your own optional function that you can pass in to generate the colors so that the hack is more generic. 


Just remember to include the right files (not the minified ones that don't contain your changes).

Comments

  1. Thanks for the information! Can you provide an example of where I would pass in my own function? Thanks!

    ReplyDelete
  2. Thanks, dude this really helps a lot!! :)

    ReplyDelete
  3. this.next = function (val, max) {
    if(!max) return 'red';
    var p = val * 100 / max;
    if(p < 33.3) return 'red';
    if(p < 66.6) return 'yellow';
    return 'green';
    };
    place where in code
    i'm example

    ReplyDelete

Post a Comment

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word