Thursday, July 25, 2013

Custom tooltips for pie charts in JqPlot

For work I added some charting behavior using the Google chart APIs. They turned out okay, but using them added a lot of work because of legal process. These APIs are not governed by an open licence but instead use a Google license. Not really a big deal from my perspective, but legal had to go over it and there were several rounds of back and forth. In less time than it took to deal with this kind of things I implemented a version using jqPlot. One of the things I worked on was making jqPlot look like Google charts. It was remarkably easy. The one thing that seemed lacking was the tooltips, but I discovered an easy trick to create custom tooltips.

Normally the jqPlot pie chart gets a JavaScript array like this [["label", 5]["another label",7]]. You can add a third element to these sub arrays and it will largely be ignored i.e. ["label",5,"ignore me"]. Turns out the typeless nature of the code has this advantage.

But this whole array is passed into the code for generating a tooltip used by the highlight plugin. Here is the code I used in the highlighter setup:

highlighter: {
    show: true,
    formatString: "%s<br><div style='display:none'>%d</div>%s",
    tooltipLocation: 'ne',
    useAxesFormatters: false
}

The important part of this is the formatString section. The basically calls a 'printf' feeding the array in as values. Normally you would only have two values available in the tooltip, but since you have added a value to the array you can access it here. It is very nice and points to the extensibility of a untyped language. There is a little bit of waste since I am generating undisplayed elements in order to mask certain values, but overall this seems like a fairly elegant way to add custom tooltips to jqPlot.


No comments:

Post a Comment