Web Charts Using jQuery Flot

Adding charts to your web application is simple using a library called ‘Flot’. Flot is a pure JavaScript plotting library for jQuery. It produces graphical plots of arbitrary datasets on-the-fly client side. During this post I will explore using the Flot library a bit.

image image

Basic Charting

First head on over to the Flot project web site and download the Flot code. Save it to a file called ‘jquery.flot.js’. Then simply add a couple of ‘script’ tags to link the library into your web page.

<!--[if IE ]>
<script type="text/javascript" src="https://bobcravens.com/wp-content/uploads/2011/01/excanvas.min.js"></script>
<![endif]-->
<script type="text/javascript" src="https://bobcravens.com/wp-content/uploads/2011/01/jquery.flot.js"></script>

Notice for IE we are including the Explorer Canvas JavaScript emulator. Next add a place holder ‘div’ element somewhere in the body element of your html.

<div id='chart1' style='width:400px;height:300px;'></div>

Fetch (or in this case create) and format some data to plot. Flot uses the following format for data:

var series1 = [ [0,0], [1,1], [2,2], [3,3], [4,4] ];
var series2 = [ [0,4], [1,3], [2,2], [3,1], [4,0] ];

var data = [ series1, series2 ];

Each point is an array of x and y values. A series is an array of points. The main method that creates plots accepts an array of series as input values. Finally create the plot using the following call:

$.plot($("#chart1"), data);

The Flot library has a good set of default for many visual elements. The above is the ‘bare-bones’ graph. Create some data, provide a place holder and create the plot.

Demo 1

Formatting Example

If you want a more control over the formatting Flot gives you plenty of hooks. Previously we discussed a series being an array of points. Flot actually allows a series to be a JavaScript object with properties. As an example the following code formats the label, line type, and color for each of the series:

var series1 = {
            label: "series 1",
            data: [ [0,0], [1,1], [2,2], [3,3], [4,4] ],
            color: "#ff0000",
            points: { show: false },
            lines: { show: false },
            bars: { show: true },
            yaxis: 1
            };
var series2 = {
            label: "series 2",
            data: [ [0,4], [1,3], [2,2], [3,1], [4,0] ],
            color: "#00ff00",
            points: { show: true },
            lines: { show: true },
            yaxis: 2
            };

There are many other options that exist. Flot also allows global configurations to be set by passing a third parameter into the ‘plot’ method.

var options = {
    legend: { show: true, position: "nw" }
            };

$.plot($("#chart2"), data, options);

In the above case, the legend is positioned in the top-left (north-west) corner of the chart.

Demo 2

Hover / Click Example

Interacting with the charts is also simple with Flot. To enable the mouse events use the following options:

var options = {
    legend: { show: true, position: "nw" },
    grid: { hoverable: true, clickable: true }
};

The ‘grid’ object above has two flags set to true that enable hover and click events. Your code can bind to these through the ‘plothover’ and ‘plotclick’ events.

$("#chart3").bind("plothover", function(event, pos, item){
    $("#hover").html("hover: x=" + pos.x.toFixed(2) + ", y1=" + pos.y.toFixed(2) + " , y2=" +  pos.y2.toFixed(2));
    if(item){
        $("#item").html("item: series=" + (item.seriesIndex + 1) + ", x=" + item.datapoint[0].toFixed(2) + ", y=" + item.datapoint[1].toFixed(2));
    }
});

$("#chart3").bind("plotclick", function(event, pos, item){
    if(item){
        msg = "item: series=" + (item.seriesIndex + 1) + ", x=" + item.datapoint[0].toFixed(2) + ", y=" + item.datapoint[1].toFixed(2);
        alert(msg);
    }
});

Both of these bindings provide three arguments to the callback function: event, pos, item.  The following is a screenshot of the console log output in firebug for those parameters.

image

The ‘plothover’ event uses this data to update two div elements (‘#hover’ & ‘#item’).

Demo 3

Dynamic Data

Flot can also be used to plot dynamically changing data. This data could will probably originate on the server and pulled to the client via an AJAX call. Here is a trivial example demonstrating how to update the chart data.

var xVal = 0;
var data = [[],[]];
var plot = $.plot( $("#chart4"), data);

function getData(){
    // This could be an ajax call back.
    var yVal1 = Math.floor(Math.random()*11);
    var yVal2 = Math.floor(Math.random()*11);
    var datum1 = [xVal, yVal1];
    var datum2 = [xVal, yVal2];
    data[0].push(datum1);
    data[1].push(datum2);
    if(data[0].length>10){
        // only allow ten points
        data[0] = data[0].splice(1);
        data[1] = data[1].splice(1);
    }
    xVal++;
    plot.setData(data);
    plot.setupGrid();
    plot.draw();
}

setInterval(getData, 1000);

In this example the ‘getData’ function would probably generate an AJAX call with a callback that does the chart update. Here, I am using the JavaScript Math functions to generate random data. This code also only keeps the 10 most recent points using the ‘splice’ function. Calling ‘setData’ on the plot object updates the data. A call to ‘setupGrid’ recalculates the grid. Finally the call to ‘draw’ re-renders the data.

Demo 4

Summary

The Flot library is very powerful and easy to use. Check out the other examples supplied by the Flot team.

Comments
  1. tom
    • rcravens
      • Nag
      • Nag
  2. Sékou
    • rcravens
      • Sékou
        • Ricardo E
          • rcravens
  3. Jaibabu
    • rcravens
  4. yashprit
  5. Gary
  6. Murali
    • rcravens
  7. ibnu
    • rcravens
  8. Asif
  9. Elie
  10. Aravind
    • rcravens
  11. Gary
    • rcravens
  12. Rob
    • rcravens
  13. Arpit Bajpai
    • rcravens
  14. tine
    • rcravens
  15. Shawn Crigger
  16. Pablo Vermeersch
  17. Skylex
  18. bahar
  19. cheap cd key
  20. Naveen
    • Manish
  21. deviated
  22. Zauberer De Pasco
  23. Anirudh Bhutani

Leave a Reply to Arpit Bajpai Cancel reply

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

*