Book Image

Instant jQuery Flot Visual Data Analysis

By : Brian Peiris
Book Image

Instant jQuery Flot Visual Data Analysis

By: Brian Peiris

Overview of this book

Data visualization and analysis is a crucial skill in many software projects. Flot uses jQuery and HTML5 to add easy and powerful visualization capabilities to any web application. Flot produces beautiful visualizations with a minimal amount of code. It is also highly configurable, extensible, and includes many plugins out of the box. A practical guide to take you through the basics of using Flot to visualize your data; the book describes Flot's functionality in dedicated sections that include code, screenshots, and detailed explanations so that you can learn to produce charts in minutes. As you progress though this book, it will guide you through real-world examples to show you how to use statistical techniques with Flot for interactive data visualization and analysis. Starting with the very basics, you will learn exactly what you need to do to display the simplest chart using Flot. This step-by-step guide takes you through Flot's many features and settings until you can finally master the techniques you'll need to apply Flot to your application's data. You'll learn to create basic point, line, and bar charts and to use Flot's stack, pie, and time plugins to create specialized chart types. Along with learning to display complex data with multiple customizable axes you will learn to make your charts interactive with Flot's crosshair plugin. Finally, this book will guide you through learning statistical techniques via the jStat JavaScript library to analyse data; along with Flot's errorbars and fillbetween plugins to display error margins and data percentiles. Instant jQuery Flot Visual Data Analysis will give you a head start so that you can add data visualization features to your applications with ease.
Table of Contents (7 chapters)

Working with axes (Should know)


The axes are the most configurable parts of the chart. Flot gives you the ability to change the position, type, and colors of the axes. It also gives you full control of the ticks and labels on the axes, letting you adjust the number of ticks and alter the formatting. Axes also determine how the data is displayed; you can change the min and max settings to display only a part of the data on the chart and you can also transform the data in various ways.

The full documentation is available at https://github.com/flot/flot/blob/master/API.md#customizing-the-axes. We will take a look at some examples of the configuration options by creating a chart that has a logarithmic axis and another chart that includes multiple axes.

Getting ready

We start with the same boilerplate that we used when creating basic charts.

How to do it...

The following code creates some sample data that grows exponentially. We then use the transform and tickSize setting on the Y axis to adjust how our data is displayed:

...
  <script>
    var data = [], i;
    for (i = 1; i <= 50; i++) {
      data.push([i, Math.exp(i / 10, 2)]);
    }

    $('#sampleChart').plot(
      [ data ], 
      {
        yaxis: {
          transform: function (v) {
            return v == 0 ? v : Math.log(v);
          },
          tickSize: 50
        }
      }
    );
  </script>
...

Flot draws a chart with a logarithmic Y axis, so that our exponential data is easier to read:

Next, we use Flot's ability to display multiple axes on the same chart as follows:

...
    var sine = [];
    for (i = 0; i < Math.PI * 2; i += 0.1) {
      sine.push([i, Math.sin(i)]);
    }
    var cosine = [];
    for (i = 0; i < Math.PI * 2; i += 0.1) {
      cosine.push([i, Math.cos(i) * 20]);
    }
    $('#sampleChart').plot(
      [
        {label: 'sine', data: sine},
        {
          label: 'cosine',
          data: cosine,
          yaxis: 2
        }
      ],
      { yaxes: [ {}, { position: 'right' } ] }
    );
...

Flot draws the two series overlapping each other. The Y axis for the sine series is drawn on the left by default and the Y axis for the cosine series is drawn on the right as specified:

How it works...

The transform setting expects a function that takes a value, which is the y coordinate of our data, and returns a transformed value. In this case, we calculate the logarithm of our original data value so that our exponential data is displayed on a linear scale. We also use the tickSize setting to ensure that our labels do not overlap after the axis has been transformed.

The yaxis setting under the series object is a number that specifies which axis the series should be associated with. When we specify the number 2, Flot automatically draws a second axis on the chart. We then use the yaxes setting to specify that the second axis should be positioned on the right of the chart.

In this case, the sine data ranges from -1.0 to 1.0, whereas the cosine data ranges from -20 to 20. The cosine axis is drawn on the right and is independent of the sine axis.

There's more...

Flot doesn't have a built-in ability to interact with axes, but it does give you all the information you need to construct a solution.

Making axes interactive

Here, we use Flot's getAxes method to add interactivity to our axes as follows:

...
    var
      showFahrenheit = false,

      temperatureFormatter = function (val, axis) {
        if (showFahrenheit) {
          val = val * 9 / 5 + 32;
        }
        return val.toFixed(1);
      },

      drawPlot = function () {
        var plot = $.plot(
          '#sampleChart',
          [[[0, 0], [1, 3], [3, 1]]],
          { yaxis: { tickFormatter: temperatureFormatter } }
        );

        var plotPlaceholder = plot.getPlaceholder();

        $.each(plot.getAxes(), function (i, axis) {
          var box = axis.box;
          var axisTarget = $('<div />');

          axisTarget.
            css({
              position: 'absolute',
              left: box.left,
              top: box.top,
              width: box.width,
              height: box.height
            }).
            click(function () {
              showFahrenheit = !showFahrenheit;
              drawPlot();
            }).
            appendTo(plotPlaceholder);
        });
      };

    drawPlot();
...

First, note that we use a different way of creating a plot. Instead of calling the plot method on a jQuery collection that matches the placeholder element, we use the plot method directly from the jQuery object. This gives us immediate access to the Flot object, which we use to get the axes of our chart. You could have also used the following data method to gain access to the Flot object:

var plot = $('#sampleChart').plot(...).data('plot');

Once we have the Flot object, we use the getAxes method to retrieve a list of axis objects. We use jQuery's each method to iterate over each axis and we create a div element that acts as a target for interaction. We set the div element's CSS so that it is in the same position and size as the axis' bounding box, and we attach an event handler to the click event before appending the div element to the plot's placeholder element.

In this case, the event handler toggles a Boolean flag and redraws the plot. The flag determines whether the axis labels are displayed in Fahrenheit or Celsius, by changing the result of the function specified in the tickFormatter setting.