jqPlot — Graphs for All Occasions

Posted on Jan 22, 2013 by Nate in Uncategorized

I’ve recently had the opportunity to work on a data-intensive project for a client using the jqPlot library. jqPlot is a jQuery library that lets you easily render almost any kind of graph you can imagine. I’ve included a screen shot of two of the graphs I worked on, but you can see just how versatile jqPlot is by checking out these examples.

One of the graphs that the client required was a stacked bar chart, which you can see below. jqPlot offers many options that will allow you to customize the graphs as needed… at least for most scenarios. In this particular example, the customer wanted data labels to show for each portion of the bar chart. That was simply a matter of doing the following: pointLabels: { show: true, location: 's' }

But the client also wanted to show the total for the stacked values above each bar, and jqPlot can’t accommodate that. With the help of Firebug (thank you Mozilla!), I was able to find the classes that jqPlot was using to draw the graphs. So I knew I could insert a div based on that information. But where to insert it? Since the values of the stacked bars can vary (greatly, in some cases), I really didn’t know how to adjust the height of each div on the fly. But (and pay attention, kids!) I realized that math could solve my problem.

jqPlot Stacked Bar Chart

First of all, when you create a chart in jqPlot, you get a “plot object,” and this is what you use to manipulate the chart once it’s been rendered. It works like this:
plot1 = $.jqplot('containerDiv', [chartDataArray], createChartOptions());

As you may have guessed, the createChartOptions() method will generate all the options you may want to pass in for this particular graph. Anyway, I realized that once the chart was created, I could pass it into another method that would grab the range of values in the graph — from 0 to 160, in this particular example. Since I also knew how large the dimensions of the chart would be (I set those limits in my container div), I could calculate how many pixels jqPlot would use for each point of data between 0 and 160. Understanding that would allow me to programmatically move my “total label” to whatever point I needed:

Code Snippet

Leave a Reply

Your email address will not be published. Required fields are marked *