Monday, February 4, 2013

Animating a Flot Graph with jQuery

The Flot homepage does have an example of animating data. Its actually moving points on and off the chart. It also uses setTimeout() to pace the animation. I was interested in easing in my bar graph so I thought I'd try something with jQuery.animate() and see what I could come up with.

I accomplished it by doing several thing:

  1. Creating the graph with the actual data I want to plot

  2. Using the step callback available in jQuery.animate()

  3. Using the Flot API functions setData and draw to update the graph

    • Here's a small snippet of code showing the basics:

      plot = $.plot($('.graph'), [init], options);

      $('.graph').animate( {tabIndex: 0}, {
      duration: 1000,
      step: function ( now, fx ) {

      var r = $.map(, function ( o ) {
      return [[ o[0], o[1] * fx.pos ]];

      plot.setData( [{ data: r }] );


      It was easiest to just create the graph from the final dataset so Flot would create the correct axises and scaling. Grab a reference to the object so it can used and then on each step in the animation, manipulate the y-axis data point to vary from zero to the final value based on fx.pos. I have a working example on my sandbox. I haven't tried it with too many other types of graphs/options yet but it seems like a pretty flexible solution to add some extra pizzazz to your graphs.