Charting over time (flotJS)

One of the more impressive features of this library is the ease with which one can update the chart information. It's very easy to see from the first moment when you review this library and its samples that the author loves math and loves charting. My favorite feature is the way the chart can update its x ranges dynamically based on the input added into it.

My second favorite feature is how easy it is to update the chart text info by using a tickFormater method:

Charting over time (flotJS)

Getting ready

To get the latest builds of the flotJS library, please visit our link hub at http://blog.everythingfla.com/?p=339 for charting open source libraries or download our book's source files where we include the latest build as of publication at http://02geek.com/books/html5-graphics-and-data-visualization-cookbook.htm.

How to do it...

Let's create our HTML and JavaScript files:

  1. Create an HTML file:
    <!DOCTYPE html>
    <html>
      <head>
        <title>flot</title>
        <meta charset="utf-8" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script src="./external/flot/jquery.flot.js"></script>
        <script src="./external/flot/jquery.flot.fillbetween.js"></script>    
        
        <script src="./07.03.flot.js"></script>
    
      </head>
      <body style="background:#fafafa">
      
        <div id="placeholder" style="width:600px;height:300px;"></div> 
      </body>
    </html>
  2. Create a new JavaScript file (07.03.flot.js) and then create our data source:
    var males = {
    
    //...
    //please grab from source files its a long list of numbers
    };Create helper variables:
    var VIEW_LENGTH = 5;
    var index=0;
    var plot;
    
    var formattingData = {
      xaxis: { tickDecimals: 0, tickFormatter: function (v) { return v%12 + "/" + (2009+Math.floor(v/12)); } },
      yaxis: { tickFormatter: function (v) { return v + " cm"; } }
    };
  3. Create a ready event and trigger updateChart:
    $(document).ready(updateChart);
  4. Create updateChart:
    function updateChart() {
      plot = $.plot($("#placeholder"), getData(), formattingData);
             
      if(index+5<males['mean'].length){
        setTimeout(updateChart,500);
      }
    }
  5. Create getData:
    function getData(){
      var endIndex = index+5>=males.length?males.length-1:index+5;
      console.log(index,endIndex);
      var dataset = [
        { label: 'Male mean', data: males['mean'].slice(index,endIndex), lines: { show: true }, color: "rgb(50,50,255)" },
        { id: 'm15%', data: males['15%'].slice(index,endIndex), lines: { show: true, lineWidth: 0, fill: false }, color: "rgb(50,50,255)" },
        { id: 'm25%', data: males['25%'].slice(index,endIndex), lines: { show: true, lineWidth: 0, fill: 0.2 }, color: "rgb(50,50,255)", fillBetween: 'm15%' },
        { id: 'm50%', data: males['50%'].slice(index,endIndex), lines: { show: true, lineWidth: 0.5, fill: 0.4, shadowSize: 0 }, color: "rgb(50,50,255)", fillBetween: 'm25%' },
        { id: 'm75%', data: males['75%'].slice(index,endIndex), lines: { show: true, lineWidth: 0, fill: 0.4 }, color: "rgb(50,50,255)", fillBetween: 'm50%' },
        { id: 'm85%', data: males['85%'].slice(index,endIndex), lines: { show: true, lineWidth: 0, fill: 0.2 }, color: "rgb(50,50,255)", fillBetween: 'm75%' }
      ];
        
        
      index++;
      return dataset;
    }

Now if you run the chart in your browser, you will see 6 months at a time, and at every half of a second, the chart will be updated by pushing the chart one month forward until the end of data source is reached.

How it works...

flotJS has a built-in logic to reset itself when its redrawn, and that's part of our magic. Our data source has been borrowed from one of the flotJS samples. We are actually using the data to represent a fictional situation. Originally this data was representing the average weight of people based on their age, broken down into percentiles. But our point in this example is not to showcase the data but instead show ways of visualizing the data. So in our case, we had to treat the data by keeping the percentiles as they are intended to be, but use the inner data to showcase the average over years instead of over ages, as follows:

{'15%': [[yearID, value], [yearID, value]...

The yearID values range from 2 through 19. We want to showcase this information as if we started our data picking from 2006. Each yearId will represent a month (19 would be 1.5 years after 2006, instead of the age 19 as the data actually represents).

So let's start breaking it down. Now that we know how we are going to treat our dataset, we want to limit the number of months that we can see at any given time. As such we will add two helper parameters, one of which will keep track of our current index and the other will track the maximum number of visible elements at any given time:

var VIEW_LENGTH = 5;
var index=0;

We will create a global variable for our Flot graph and create a formatter to help us format the data that will be sent in.

var plot;
var formattingData = {
  xaxis: { tickDecimals: 0, tickFormatter: function (v) { return v%12 + "/" + (2003+Math.floor(v/12)); } },
  yaxis: { tickFormatter: function (v) { return v + " cm"; } }
};

Note that tickFormater enables us to modify the way our tick will look in the chart. In the case of the x axis, the goal is to showcase the current date 2/2012..., and in the y axis, we want to add cm to the numbers that will be printed out on the screen.

There's more...

There are still two more things to cover—the getData function and the updateChart function.

The GetData function

In flotJS every data point has an ID. In our case, we want to showcase six related content types. Play around with the parameters to see how they change the way the view is rendered. Before we send the created array back, we update the index ID by one, so the next time that the function is called it will send the next range.

One more thing we need to note is the actual data range. As we are not sending the full data range (but a maximum of 5), we need to validate that there are atleast five items after the index, and if not we will return the last element of the array, ensuring that we never slice more than the actual length:

var endIndex = index+5>=males.length?males.length-1:index+5;

The UpdateChart function

This part is probably the simplest one. The same code is used for the first render and all the following renders. If the dataset is valid, we create a timeout and call this function again until the animation completes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.188.36