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="http://bobcravens.com/files/excanvas.min.js"></script>
<![endif]-->
<script type="text/javascript" src="http://bobcravens.com/files/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.

This entry was posted in jQuery, javascript, web. Bookmark the permalink.

41 Responses to Web Charts Using jQuery Flot

  1. Pingback: Tweets that mention Web Charts Using jQuery Flot | Random Sparks -- Topsy.com

  2. tom says:

    Hi how do you put a legend into the dynamic data chart.

    • rcravens says:

      I have updated the example to include a ‘dynamic data 2′ chart. This chart has a legend. View source on the page to get the full code. His is the URL:

      http://bobcravens.com/demos/flot/index.html

      Bob

      • Nag says:

        Hi Bob, I am trying to generate Dynamic data graph with multi aces( one xaxis, two yaxes). I used the sample code of DynamicData code that you here and customized one of the data series so that second data series should bind to yaxis:2 on the right side. But, when I am executing the code it always displaying graph based on yaxis:1, which was default. I would like to see second series bound to yaxis:2, please share what changes I need to make. Appreciate your immediate response.

        Here I am copying the whole code:

        Multi Axes-Multi Series-Realtime Graph

        Multi Axes-Multi Series-Realtime Graph

        var xVal = 0;
        var inputdata = [[], []];
        var options = { xaxes: [{}],
        yaxes: [{}, { show: true, position: "right"}]
        }
        var plot = $.plot($(“#placeholder”), [{ data: inputdata[0], label: “series 1″ }, { data: inputdata[1], label: “series 2″, yaxis: 2}], options);

        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];
        inputdata[0].push(datum1);
        inputdata[1].push(datum2);
        if (inputdata[0].length > 10) {
        inputdata[0] = inputdata[0].splice(1);
        inputdata[1] = inputdata[1].splice(1);
        }
        xVal++;
        alert(“inputdata :” + inputdata);
        plot.setData(inputdata);
        plot.setupGrid();
        plot.draw();
        }
        setInterval(getData, 1000);

      • Nag says:

        Hi Bob,
        Could you please let me know how can we implement Dayanic data source code that you had here to use on multile y-axis. I tried it with passing yaxis:2 in [data] for plot variable, but it doesn’t work. It worked fine when I call plot() method for the same data without dynamic feature. But it’s failing with dynamic way by calling plot with these methods for dynamic feature
        plot.setData(data);
        plot.setupGrid();
        plot.draw();

        Are we loosing the yaxis:2 property by calling any of these 3 methods. Please let me know how shuold I fix this. Really appreciate your response.

        Thanks

  3. Sékou says:

    Hi Bob,
    I would like to know if the Flot could plot data from mysql database?
    Presently i am using it in one of my project and i am having hard time
    to get my data from a database.

    Thanks for your time!!

    • rcravens says:

      You will need to break the problem down into two parts: get the data from the db and provide it to Flot. Sounds like you are having issues with the ‘get the data from the db’ part. Not certain what is going on there, but once you have the data it will need to be provided to Flot in the proper format. Once the data is in the proper format, I see no reason why Flot can’t plot it.

      Bob

      • Sékou says:

        thanks a lot it works perfectly, as you said, as you said i first had to get data from the db and then i provide them to Flot.

        • Ricardo E says:

          I’m able to get the data from a MySQL database, but I don’t know how to send the data to flot, could you give an example please?

          • rcravens says:

            Hi Ricardo,

            Once you have the data from MySQL using (PHP, C#…etc) you then need to render it into your HTML in the format shown in the post. The format accepted by flot is an array of series where each series is an array of points with each point being an array of two numbers. Hope that helps.

            Bob

  4. Jaibabu says:

    Hai Bob,

    Is there any way to save the chart as image into the server on the fly while displaying it on the web page.
    I am in need of to export this type of chart and some text in the webpage into PDF/Excel/Powerpoint. So if i store the chart as image on the fly into the server then i can access that image and write it into PDF through some Java code.
    Is there any way to save the displayed chart as image programatically.

    Thanks
    Jaibabu

    • rcravens says:

      Since these charts a generated on the client I don’t know of a way to do what you are asking. In an application I have at work, I render the charts on the server side. Server side rendering could be modified to save the image.

  5. yashprit says:

    hey i need to create a graph that will have multiple y-axis and local time-stamp on x axis graph will be update after 1 second. till here i don’t have any issue i am able to get this result now i have two problem
    1. how many tick should be there on x-axis as i don’t have any control over it it depends on a condition when my input = output at that instance of time graph will stop will show that as final result.
    2. how to create fixed size of tick on y axis and how can i zoom them on y-axis tick

    could you please tell me anything in this will be great help
    Thank you

  6. Gary says:

    Hi Bob,

    My requirement is to display other details in hover event. I have all details in my presentation layer, but in tooltip i m not able to access those details. Is it possible to get more details in hovering event than details on the x-axis and Y-axis.

    I am trying to get more than 2 values in plotting

    data: [ [0,0,13], [1,1,14], [2,2,15], [3,3,16], [4,4,16] ]

    so that i can acees them like this in javascript.

    item.datapoint[2].

  7. Murali says:

    Hi Bob,

    I have a requirement where I need to add a series to already existing data in plot for every iteration of for loop. Is there a method to add series to already existing data.

    • rcravens says:

      Hi Murali,

      The last example on this post shows one way to inject in dynamic data. In this example, I add the new data to the end of the array (lines 11 and 12) and then force flot to refresh the drawing (lines 19-21). I suspect that you will do something similar.

      Bob

  8. ibnu says:

    Hi Bob….

    Can we exports the result from jquery chart to pdf?

    I allrady many libs, however until now I still cann’t export jquery chart to pdf.

    Thank’s

    • rcravens says:

      Since PDF is just a file format, you can always transform the chart into a PDF format. Most likely then the chart will be a bitmap embedded in the PDF. There are PDF libraries that help you do this. A while back I wrote something that emitted PDF files. It is not that hard to do, but nothing that is a part of the Flot library. You could try using one of those ‘print to PDF’ plugins.

  9. Asif says:

    Hello Bob,

    How do you put the corresponding values on bars in the graph?

    Thanks

  10. Elie says:

    Nice samples. I noticed that one of the sample highlihts the Bars when hovering over series ’1′. Can’t you do the same for the line series? Basically I am trying to have a similar highlighting effect on hover for a line chart.

  11. Aravind says:

    Hi,
    I want to create flot chart using date(coming from database) as one axis and string (from database),how can I achieve this..please reply back soon..thnk u..

  12. Gary says:

    Hi there, great post. I am really struggling to display mySQL table into flot format, know its not really for you to answer but wonder if you could provide a step by step, cant locate this info anywhere on web!

    So far I have 1 php page that displays a recordset of all my table records. How exactly would I create a chart page to display this data using flot? Sorry for basic question, I have been searching for answer for days now!

    Thanks

    Gary

    • rcravens says:

      Hi Gary,

      Thanks for stopping by. The flot data format is:

      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 series is an array of arrays with the x,y values in the inner array. You need to query your database and get into this format. Sounds like you already have the query, so a transformation into the appropriate format should do the trick.

      Hope this helps.

      Bob

  13. Rob says:

    Hi,

    Do you know of a way to have the plot resize properly while using something like your dynamic data example? When I try resizing (with the flot resize plugin), it works properly, until the plot.draw() function runs in the next interval. Once this function runs, the plot area keeps its new ‘resized’ size, but the data takes on its original size and the axis labels are in the wrong place. Do you know of any way around this?

    Thanks!

  14. Arpit Bajpai says:

    Hi i tried using flot in my project, but when i run the application. It is not showing me anything. I made a new ASP.net project, copied the javascript files in Scripts folder of project and in the webpage i copied the code of basic.html

  15. tine says:

    hello,
    how can i export the chart to pdf or png ???

    • rcravens says:

      Sorry, I don’t have a good way of accomplishing this. If I had this requirement, then I would probably do the following:

      1. Do a google search for any canvas to png/pdf conversions.

      2. If that doesn’t pan out, provide a server side solution that generates the png/pdf and supply a ‘download’ link on the client to fetch it.

      Bob

  16. I just wanted to say thanks for your article on using the Flot charting library for jQuery, I personally found your article quite informative and easy to read which made my conversion of a old Am Flash Charts library over to a better JavaScript based method.

  17. Pablo Vermeersch says:

    Hello. I just want to say thanks for the article. It’s very ilustrative specially with the examples and very easy to read and understand too.
    Thanks for your work, it really helped me.

  18. Pingback: Realtime chart using flot jquery | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

  19. Skylex says:

    Hi, great tutorial, I want to use data from mysql, but I don’t know how to insert the php variable in the jquery, do you have an example?
    var series1 = [ [0,0], [1,1], [2,2], [3,3], [4,4] ];
    var series2 = [ [0,4], [1,3], [2,2], [3,1], [4,0] ];
    I want to insert the php variable where are the numbers:
    var series1 = [ [$data1,$data2], [$data3,$data4];
    can you give me an example, thanks you so much.

  20. bahar says:

    thanks a lot

  21. cheap cd key says:

    Hi, i have the same question as the other poster.

    var series1 = [ [0,0], [1,1], [2,2], [3,3], [4,4] ];
    var series2 = [ [0,4], [1,3], [2,2], [3,1], [4,0] ];
    I want to insert the php variable where are the numbers:
    var series1 = [ [$data1,$data2], [$data3,$data4];
    can you give me an example, thanks you so much.

  22. Naveen says:

    I want to draw the jquery graphs using web services. Please help me………………………..I am a beginner

  23. deviated says:

    Just want to say thank you. I spent hours trying to do this without success and finally found this on google search.

    Didn’t know it would be so easy. I have a question can i share this on my blog ? of course with credits.

    -Steyn

  24. Thank you, I’ve been searching for facts about this subject for ages and yours is the best I’ve found so far.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>