Unmaintained

CanvasGraph is now replaced by PlotKit which offers the same functionality as CanvasGraph but also includes SVG support and preliminary event support. CanvasGraph will not be updated any more.

There is now a PlotKit mailing list for thos who are interested in using or further development with graphing in Javascript.

- Alastair Tse (21st March 2006)

Introduction

Canvas Graph is a small simple javascript library that allows you to conveniently plot simple line, bar and pie charts using the new HTML Canvas Tag.

The motivation for this work is to allow simple graph plotting in Javascript without resorting to anything but your web browser. I'd like the library to be simple enough for someone who knows very little Javascript to be able to use, but extendable so that people who know what they're doing to make great looking graphs for their sites.

Don't know what the Canvas HTML Tag is? Learn more about the Canvas Tag below. Also if you want to know why this is using Canvas tag rather than SVG?

Pages that Use CanvasGraph

Requirements

Note: This does not work on Internet Explorer.

Features

  • Plot bar charts, line graphs and pie charts
  • Plot multiple datasets on one graph.
  • Data input from javascript arrays, or even automatically extracting data from HTML tables or text files.
  • Flexible customisable layout and colour scheme.
  • Fully documented and open source.
  • Unit Tests

Download

Current Version: CanvasGraph.js - 0.7 (Last Updated: 13th Jan 2006)

  • 0.7 current (13th Jan 2006) - Major reorganisation. Moved into own namespace so it can work with Dojo and other strict frameworks without polluting the global namespace.
  • 0.6 old (27 Dec 2005) - Major bugfix release. Fixed bar charts with proper positioning and handle single value datasets. Added flexibility with pie chart inputs.
  • 0.5.1 old (16 Dec 2005)- Minor bugfix with drawGrid when using custom colors. (Thanks to Philippe Marschall)
  • 0.5 (11 Dec 2005) - Initial Public Release

Examples

If there are no graphs in the examples, it means your browser does not support the canvas tag. You can test your browser's support of the canvas tag here.

Below are basic example graphs that can be plotted by CanvasGraph. Note that you need a compatible browser to view them.

Unit Tests Page

Here is a constantly updated Unit tests page to prevent regressions between versions, and also demonstrate some basic plotting.

Dynamic Graph Page

Dynamic Graph Generation using Javascript and Tables.

Simple line plot of two data sets: square numbers and 2 * square numbers

View Source: LinePlotDemo.js

Simple bar chart of 1 data set with custom labels

View Source: BarChartDemo.js

Simple pie chart of powers of 2.

View Source: PieChartDemo.js

Data from a table

xx2x!sqrt(x)
0000
1111
2421.414
3961
416242
5251202.23

View Source: TableBarChartDemo.js

Screenshots

Here are some examples of the same graph above rendered in Mozilla Firefox 1.5 under Mac OS X.

CanvasGraph Line Plot
CanvasGraph Bar Chart
CanvasGraph Pie Chart

Documentation

CanvasGraph.js consists of just one single class that you should use, the CanvasGraph object.

CanvasGraph Class Functions

  • CanvasGraph.isSupported(canvas_name)

    Returns true if canvas tag is supported in the current browser, otherwise false. The optional parameter canvas_name can be used to specify the id of a canvas tag that is already in the document.

CanvasGraph Object Methods

  • CanvasGraph(id_of_canvas) - constructor

    This creates an instance of the CanvasGraph by passing it the Canvas ID that is in the HTML which is will draw to. NOTE: You must enclose the canvas tag in a div for labels to be drawn correctly.

    In HTML:

                <div><canvas width="100" height="100" id="piechart"></canvas></div>
                

    In Javascript:

                var graph = new CanvasGraph("piechart");
                
  • .setDataset(name, dataset_array)

    Adds a dataset to the graph. name is the name which you will refer to the dataset, and dataset_array is the data which you'd like to plot. This needs to be in the form of an array of (x, y) values. If a dataset of the same name already exists, it will be overwritten with the new values.

    Example:

                graph.setDataset("powers of 2", [[0, 1], [1, 2], [2, 4], [3, 8]]);
                
  • .setDatasetFromTable(name, table, xcol = 0, ycol = 1)

    Adds a dataset from a table by giving the table element and the xcol and ycol numbers starting from 0. name is the name of the dataset you will refer to and table is the DOM object representing the table that is holding the data you wish to plot. xcol and ycol are optional parameters to point to which columns the x and y values are in respectively.

    Example:

                var datatable = getElementById("squarenumbers");
                graph.setDatasetFromTable("squares", datatable, 0, 1);
                
  • .drawGrid(pixel_size, color = Color.grayColor())

    Draws a light colored grid of pixel_size width. color is an optional argument that represents the colour the grid is draw with. color must be an Mochikit.Color instance.

    Example:

                graph.drawGrid(10, Color.blueColor());            
                graph.drawGrid(100, Color.redColor());
                
  • .drawBarChart(dataset_properties)

    Draws a bar chart using the properties given in dataset_properties. dataset_properties needs to be an associative array (or dictionary) whose keys is the dataset_name and the values is the color which is used to plot the values.

    Example:

                graph.drawBarChart({"squares": Color.blueColor(),
                                    "powers of 2": Color.redColor()});
                
  • .drawLinePlot(dataset_properties)

    Draws a line plot using the properties given in dataset_properties. dataset_properties needs to be an associative array (or dictionary) whose keys is the dataset_name and the values is the color which is used to plot the values.

    Example:

                graph.drawLinePlot({"squares": Color.blueColor(),
                                    "powers of 2": Color.redColor()});
                
  • .drawPieChart(name_dataset)

    Draws a Pie Chart in the middle of the canvas with the data from the y-values of the data corresponding to the name given in the argument dataset.

    Example:

                graph.drawLinePlot("squares");
                

CanvasGraph Object Attributes

propertydescriptionexample
padding assoicative array: padding from the edge of the canvas to where the graph is drawn. {top: 10, left: 30, bottom: 30, right: 20}
xlabels/ylabels associative array: mapping from xvalues/yvalues to label strings. {1: "one", 2: "two", 3: "three"}
xticks/yticks array: where we put ticks in the axis, these are in dataset units. only set these if you have set autoAxis = False [0, 10, 20, 30]
autoAxis boolean: automatically calculate axis. false/true
originIsZero boolean: make origin 0. false/true
barChartWidth float: each x-value is allocated a width for a bar chart, this determines how much of that width is actually used to draw the bars. 0.75
fontSize int: font size to draw labels in pixels. 10
xtickSeparation/ytickSeparation int: minimum amount of pixels between xticks/yticks. used only when autoAxis = true. 100
labelColor Mochikit.Color: Color of labels on axis. For pie charts, this will be the same color as the pie slice if labelColor = null Color.blackColor()

Learn more about the HTML Canvas Tag

Canvas Tag was first introduced by Apple as an extension to HTML in order to allow more expressive use of Javascript and HTML in their Apple Dashboard Widgets. It was subsequently introduced to the WHATWG workgroup and proposed in their draft standard.

Related Links:

Canvas Tag vs SVG

Probably the first thing someone asks is why bother with Canvas tag and not do it with SVG?

Good point. It just so happens that my primary browsers are Safari and Mozilla Firefox, and the thing they have in common is the Canvas Tag, and unfortunately not SVG.

Secondly, I'm reasonably competent at the stack based graphics API like OpenGL that is presented with the Canvas Tag. So doing graphing is a piece of cake for me in that API, whereas I don't even know where to start with SVG.

With that said, I will like to do an SVG version eventually. As long as I'm allowed to construct the SVG DOM directly from Javascript, then it shouldn't be hard (in fact trivial) to do it in SVG. Watch this space for more -- or at least I have to change the name of this project!

About

By: Alastair Tse [alastair^tse.id.au]

License: BSD License


You can reply to me about this on Twitter: