Wednesday, October 9, 2024

Easy HTML5 Charting with PlotKit

Easy HTML5 Charting with PlotKit

With browser support for both the HTML5 Canvas and SVG on the rise, it should not come as a surprise that libraries have begun cropping up to help us turn our data into visually dazzling HTML charts. One such library that I recently gave a try is PlotKit by liquidx – aka Australian Google iOS Developer Alastair Tse. It includes support for both the HTML5 Canvas and SVG via Adobe SVG Viewer as well as an emulated canvas for Internet Explorer. PlotKit can be readily extended to include other rendering engines, styles and layouts and is licensed under the BSD License, so you can include it in both free and commercial applications without fear of being sued! That last part is what first piqued my interest, since I am looking to use it in a commercial app that I’m currently developing.

Canvas vs. SVG

It just so happens that I wrote an article comparing the HTML5 Canvas to SVG, called HTML5 Canvas vs. SVG: Choose the Best Tool for the Job. To recap, SVG is vector-based, relies on XML files for configuration, and is better for drawing text, whereas the Canvas manipulates pixels, is a pure scripting solution, and is best for dynamic charting. Canvas and SVG share similar support across modern browsers: Canvas is supported by Opera 9, Safari 2 and Firefox 1.5, while SVG is supported by IE 9, Firefox 14, Chrome 21, Safari 6, and Opera 12. PlotKit uses a degraded Emulated Canvas mode for IE.


A Simple Canvas Example

PlotKit requires four of its own script files as well as well as the MochiKit library, on which it’s built:

 <html>
  <head>
    <script type="text/javascript" src="/mochikit/MochiKit.js"></script>
    <script type="text/javascript" src="/plotkit/Base.js"></script>
    <script type="text/javascript" src="/plotkit/Layout.js"></script>
    <script type="text/javascript" src="/plotkit/Canvas.js"></script>
    <script type="text/javascript" src="/plotkit/SweetCanvas.js"></script>
  </head>

You’ll also need to add a <canvas> tag where you want the graph to appear. Notice that PlotKit requires the <canvas> tag to be enclosed inside <DIV> tags in order for labels to work:

 <div><canvas id="chart" height="400" width="650"></canvas></div>

Drawing the chart can be accomplished in two easy steps: first, create a layout with data:

//create a new layout object, and tell it that we want a bar chart
var layout = new PlotKit.Layout(“bar”, {});

//add a new dataset to the layout

//(You can add multiple datasets by specifying a different name in the first parameter for each dataset)
layout.addDataset(‘monthlyData’, [[0,12],[1,13],[2,16],[3,15],[4,16],[5,19],[6,19],[7,12],[8,23],[9,16],[10,13],[11,24]]);

//tell the layout to calculate the layout of the chart
layout.evaluate();

The second step is to create the renderer:

//get the canvas element

var canvas = MochiKit.DOM.getElement(“chart”);

//create the renderer to work on the canvas object, using our layout and data

var plotter = new PlotKit.SweetCanvasRenderer(canvas, layout, {});

//render the chart!

plotter.render();

Additional Options

You probably noticed that we passed an empty object ({}) as the second argument to the Layout() and SweetCanvasRenderer() constructors. They share a collection of named options, which saves us from having to specify which object each option is for. There are too many to list here, but here are a few good ones that can really affect the look of your charts:

  var options = {
   "colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[4]),
   "padding": {left: 30, right: 0, top: 10, bottom: 30},
   "xTicks": [{v:0,  label:"Jan"},
              {v:1,  label:"Feb"},
              {v:2,  label:"Mar"},
              {v:3,  label:"Apr"},
              {v:4,  label:"May"},
              {v:5,  label:"Jun"},
              {v:6,  label:"Jul"},
              {v:7,  label:"Aug"},
              {v:8,  label:"Sep"},
              {v:9,  label:"Oct"},
              {v:10, label:"Nov"},
              {v:11, label:"Dec"}],
   "barWidthFillFraction": 0.55,
   "yAxis": [0, 25]
  };
  MochiKit.DOM.addLoadEvent(function() {
    var layout = new PlotKit.Layout("bar", options);
    //...
    var plotter = new PlotKit.SweetCanvasRenderer(canvas, layout, options);
    //...
  });
  • The colorScheme controls the colors of the chart’s data components – that is the lines, bars, pie, as opposed to the background. It accepts one of the “MochiKit.Color.Color”s defined in the PlotKit.Base.palette Array.
  • The padding applies to the graph, but not the labels. It’s an object with properties of top, bottom, left, right in pixels.
  • The xTicks actually does two things. As an array of {label: “somelabel”, v:value} objects, it sets the X axis tick values as well as their associated labels. I used it to set the Month names.
  • The barWidthFillFraction determines the amount of space that each bar should consume per X value. Thus, numbers under 1 produce thinner bars, while those above 1 create wider ones.
  • The yAxis property sets the minimum and maximum values for the Y axis, using an array of 2 floating point numbers. I find it useful to give the chart a little breathing room at the top.

Conclusion

There are more fanciful and feature-rich charting libraries to be had, but for simple charting, PlotKit is a great choice! As long as you’re not looking to dramatically customize the chart elements like trying to turn it into 3D, PlotKit is more than capable of delighting you and your audience.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured