SVG Graphing

The jQuery SVG graphing extension (jquery.svggraph.js) provides support for drawing graphs with SVG.

The SVG graphing entry point is within the SVG wrapper object as svg.graph, which allows you to configure the graph and render it using SVG. Many functions return the graph object so that further calls may be chained together.

var defs = svg.defs();
svg.linearGradient(defs, 'fadeBlue', [[0, 'lightblue'], [1, 'blue']]);
svg.linearGradient(defs, 'fadeRed', [[0, 'pink'], [1, 'red']]);
svg.linearGradient(defs, 'fadeGreen', [[0, 'lightgreen'], [1, 'green']]);
svg.graph.noDraw().title('Browser Usage').
	addSeries('IE', [95.97, 91.80, 88.16, 86.64], 'lightblue', 'blue', 3).
	addSeries('Netscape', [3.39, 2.83, 1.61, 0.00], 'pink', 'red', 3).
	addSeries('Firefox', [0.00, 4.06, 8.13, 9.95], 'lightgreen', 'green', 3).
	format('ivory', 'gray').
	gridlines({stroke: 'gray', strokeDashArray: '2,2'}, 'gray').
	status(setStatus);
	
svg.graph.noDraw().
	xAxis.title('Year').scale(0, 3).
		ticks(1, 0).labels(['2002', '2004', '2005', '2006']).end().
	yAxis.title('Percentage').scale(-5, 105).ticks(10, 5).end().
	legend.settings({fill: 'lightgoldenrodyellow', stroke: 'gray'}).
		show(legendPos).area(legendArea[legendPos]).end().
	series(0).format(fills[0][seriesFill]).end().
	series(1).format(fills[1][seriesFill]).end().
	series(2).format(fills[2][seriesFill]).end().
	area(chartArea[legendPos]).
	type(chartType, {explode: 2, explodeDist: 10}).redraw();

addSeries | area | chartArea | chartFormat | chartOptions | chartType | container | format | gridlines | noDraw | options | redraw | series | status | title | type

SignatureReturnsComments
addSeries(name, values, fill, stroke, strokeWidth, settings) graph object Add a series of values to be plotted on the graph. The details are encapsulated in a SVGGraphSeries object.

name (string, optional) is the name of this series.

values (number[]) is the values to be plotted.

fill (string) is how the plotted values are filled. The default is 'green'.

stroke (string, optional) is the colour of the plotted lines. The default is 'black'.

strokeWidth (number, optional) is the width of the plotted lines. The default is 1.

settings (object, optional) is additional settings (SVG attributes) for the plotted values.

svg.graph.addSeries('Firefox', [0.00, 4.06,
	8.13, 9.95], 'lightgreen', 'green', 3);
area(left, top, right, bottom) graph object or number[4] Set the insets for the main chart area. If the parameter value is less than or equal to 1 it is taken as the proportion of the width/height. If more than 1 it is the number of pixels.

left (number) is the left position or (number[4]) all the positions in an array.

top (number) is the top position (omitted if left is an array).

right (number) is the right position (omitted if left is an array).

bottom (number) is the bottom position (omitted if left is an array).

svg.graph.area(0.1, 0.1, 0.9, 0.8);

If no parameters are provided, the function returns the current chart area.

var area = svg.graph.area();
alert(area[0] + ',' + area[1]);

Since 1.3.0 - previously you used chartArea.
chartArea(left, top, right, bottom) graph object or number[4] Since 1.3.0 - deprecated in favour of area.
chartFormat(fill, stroke, settings) graph object or format object Since 1.3.0 - deprecated in favour of format.
chartOptions(options) graph object or options object Since 1.3.0 - deprecated in favour of options.
chartType(id, options) graph object or string Since 1.3.0 - deprecated in favour of type.
container(cont) graph object or SVG element Set the container, which should be a svg element, for the graph elements. A default container is created automatically.

cont (SVG element) is the new graph container.

svg.graph.container(svg.svg(0, 0, 600, 350));

If no parameters are provided, the function returns the current chart container.

var cont = svg.graph.container();

Since 1.3.1.
format(fill, stroke, settings) graph object or format object Set the background of the graph chart.

fill (string) is how to fill the chart background.

stroke (string, optional) is the colour of the outline.

settings (object, optional) is additional formatting (SVG attributes) for the chart background.

svg.graph.format('ivory', 'gray', {fillOpacity: 0.5});

If no parameters are provided, the function returns the current chart format, with at least the fill attribute.

var format = svg.graph.format();
alert(format.fill);

Since 1.3.0 - previously you used chartFormat.
gridlines(xSettings, ySettings) graph object or object[2] Set the gridlines formatting for the graph chart.

xSettings (string) is the colour of the gridlines along the x-axis, or (object) formatting (SVG attributes) for the gridlines along the x-axis, or null for none.

ySettings (string) is the colour of the gridlines along the y-axis, or (object) formatting (SVG attributes) for the gridlines along the y-axis, or null for none.

svg.graph.gridlines('yellow',
	{stroke: 'green', strokeWidth: 2});

If no parameters are provided, the function returns the current gridline format objects.

var gridlines = svg.graph.gridlines();
alert(gridlines[0].stroke);
noDraw() graph object Suppress drawing of the graph until redraw() is called. Normally the graph is redrawn whenever anything changes, but this function allows multiple changes to be made before redrawing.

svg.graph.noDraw();
options(options) graph object or options object Set additional options for the particluar chart type.

options (object) is the extra options.

svg.graph.options({explodeDistance: 15});

If no parameters are provided, the function returns the current chart options.

var options = svg.graph.options();

Since 1.3.0 - previously you used chartOptions.
redraw() graph object Redraw the entire graph with the current settings and values. Normally the graph is redrawn whenever anything changes, but this function signals a redraw after pausing it with noDraw().

svg.graph.redraw();
series(i) SVGGraphSeries or SVGGraphSeries[] Retrieve a single series or the current set of series to be plotted on the graph.

i (number, optional) is the index of the required series.

var series = svg.graph.series(0);

If no parameters are provided, the function returns the list of all series.

var allSeries = svg.graph.series();

Since 1.3.0 - added index.
status(onstatus) graph object Set the callback function for status updates. When the mouse hovers over a series, a call is made to this function with the series name and the current value as parameters. On mouse exit the function is called with blank and zero values.

onstatus (function) is the callback function.

svg.graph.status(setStatus);

Since 1.4.3 - function no longer has to be global and now takes two parameters.
title(value, offset, colour, settings) graph object or object Set the title of the graph.

value (string) is the title.

offset (number, optional) is the pixel offset from the top of the chart.

colour (string, optional) is the fill colour for the title.

settings (object, optional) is formatting (SVG attributes) for the title.

svg.graph.title('Browser usage',
	'blue', {stroke: 'yellow'});

If no parameters are provided, the function returns the current title settings as an object with value, offset, and settings attributes (colour appears in settings as fill).

var title = svg.graph.title();
alert(title.value);

Since 1.4.2 - added colour.
type(id, options) graph object or string Set the type of chart to be rendered. See $.svg.graphing.chartTypes() for the list of available types.

id (string) is the ID of the chart type.

options (object, optional) is additional settings for this chart type.

svg.graph.type('pie', {explode: 1});

If no parameters are provided, the function returns the current chart type.

var type = svg.graph.type();

Since 1.3.0 - previously you used chartType.

The following functions are intended for internal use by chart renderers. They would be called from within the drawGraph() function via the graph parameter.

_drawAxes | _drawAxis | _drawChartBackground | _drawGridlines | _drawLegend | _drawTitle | _getDims | _getPercentageAxis | _getTickOffsets | _getTotals | _showStatus

SignatureReturnsComments
_drawAxes(noX) null Draw the axes in their standard configuration.

noX (boolean, optional) is true to suppress the x-axes, false to draw it.

graph._drawAxes();
_drawAxis(axis, id, x1, y1, x2, y2) null Draw an axis and its tick marks.

axis ( SVGGraphAxis) is the axis definition.

id (string) is the identifier for the axis group element.

x1 (number) is starting x-coodinate for the axis.

y1 (number) is starting y-coodinate for the axis.

x2 (number) is ending x-coodinate for the axis.

y2 (number) is ending y-coodinate for the axis.

graph._drawAxis(new SVGGraphAxis(
	'', 0, 100, 10, 0), 'yAxis', dims[X],
	dims[Y], dims[X], dims[Y] + dims[H]);
_drawChartBackground(noXGrid, noYGrid) background element Draw the chart background, including gridlines.

noXGrid (boolean, optional) is true to suppress the x-gridlines, false to draw them.

noYGrid (boolean, optional) is true to suppress the y-gridlines, false to draw them.

var bg = graph._drawChartBackground();
_drawGridlines(bg, axis, horiz, dims, format) null Draw one set of gridlines.

bg (element) is the background group element.

axis ( SVGGraphAxis) is the axis definition.

horiz (boolean) is true if horizontal, false if vertical.

dims (number[4]) is the left, top, width, height of the chart area.

format (object) is additional settings for the gridlines.

graph._drawGridlines(bg, graph.yAxis,
	false, dims, graph._gridlines[0]);
_drawLegend() null Draw the chart legend based on its settings.

graph._drawLegend();
_drawTitle() null Draw the graph title - centred at the top.

graph._drawTitle();
_getDims(area) number[4] Calculate the actual dimensions of the given area. Convert the chart area settings into actual coordinates returned in an array: left, top, width, height.

area (number[4], optional) is the area sizings (left, top, right, bottom), defaults to main chart area.

var dims = graph._getDims();
_getPercentageAxis() SVGGraphAxis Retrieve the standard percentage axis (localised).

graph._drawGridlines(
	bg, graph._getPercentageAxis(),
	true, dims, graph._gridlines[0]);
_getTickOffsets(axis, bottomRight) number[2] Calculate offsets based on axis and tick positions. Returns the array of offset multipliers (-1..+1) for left/up and right/down strokes.

axis ( SVGGraphAxis) is the axis definition.

bottomRight (boolean) is true if this axis is appearing on the bottom or right of the chart area, false if to the top or left.

var offsets =
	graph._getTickOffsets(axis, true);
_getTotals() number[] Retrieve the totals for each entry across all the series. This can be used in charts that show relative proportions, such as stacked columns or rows, and pie charts.

var totals = graph._getTotals();
_showStatus() object Retrieve the SVG attributes for onmouseover and onmouseout events that display the current series value status. Add this to your SVG element depicting the series value.

graph._wrapper.rect(g, x, y, w, h,
	graph._showStatus(series._name + ' ' +
	series._values[i]));

The following variables are available for general use.

NameTypeComments
legend SVGGraphLegend The chart's legend.

svg.graph.legend.settings(
	{fill: 'lightgoldenrodyellow', stroke: 'gray'});
xAxis SVGGraphAxis The chart's main x-axis.

svg.graph.xAxis.title('Year');
x2Axis SVGGraphAxis The chart's secondary x-axis. Not yet implemented.

svg.graph.x2Axis.title('Region');
yAxis SVGGraphAxis The chart's main y-axis.

svg.graph.yAxis.title('Percentage');
y2Axis SVGGraphAxis The chart's secondary y-axis. Not yet implemented.

svg.graph.y2Axis.title('Rates');

The following variables are intended for internal use by chart renderers. They would be used from within the drawGraph() function via the graph parameter.

NameTypeComments
_area number[4] The sizing for the main chart area. Convert these into actual dimensions with _getDims().

var dims = graph._getDims(graph._area);
_chartFormat object The format settings for the main chart area.

graph._wrapper.rect(bg, 0, 0, 600, 400, graph._chartFormat);
_chartCont SVG element The SVG element that contains all the charting elements.

graph._wrapper.rect(graph._chartCont, ...);
_chartOptions object Additional options set for the current chart type.

var explode = graph._chartOptions.explode;
_gridlines object[2] The format settings for the x- and y-gridlines.

graph._drawGridlines(bg, graph._getPercentageAxis(),
	true, dims, graph._gridlines[0]);
_series SVGGraphSeries[] The series to be plotted.

for (var i = 0; i < graph._series.length; i++) {
	...graph._series[i]...
}
_title object Details about the graph title.

graph._title.value;
_wrapper SVGWrapper The attached SVG wrapper.

graph._wrapper.rect(...);

Since 1.2.0 - previously you used _root.

Similarly for these constants.

NameTypeComments
H number The index into the dimensions array (_getDims()) for the height.

dims[graph.H]
W number The index into the dimensions array (_getDims()) for the width.

dims[graph.W]
X number The index into the dimensions array (_getDims()) for the x-coordinate.

dims[graph.X]
Y number The index into the dimensions array (_getDims()) for the y-coordinate.

dims[graph.Y]
SVG Graphing Manager

The SVG graphing manger is accessed via the $.svg.graphing object. It manages the renders for different graph formats. Assign a renderer to a particular graph with the following:

svg.graph.setGraphType('column');

Functions

SignatureReturnsComments
addChartType(id, chartType) null Add a new chart rendering type to the package. The rendering object must implement the following functions: title(), description(), options(), drawGraph(graph).

id (string) is the ID of this graph renderer.

chartType (object) is the object implementing this graph type.

$.svg.graphing.addChartType('column', new SVGColumnChart());
chartTypes() renderer array Retrieve the list of chart types.
Returns the array of chart types indexed by ID.

var chartTypes = $.svg.graphing.chartTypes();
for (var id in chartTypes) { ... }

Variables

NameTypeComments
region object The current regional settings from below.

$.svg.graphing.region = $.svg.graphing.regional['fr'];
regional object[string] Regional localisations. Each entry is an object with the following attributes: percentageText. Entries are indexed by the ISO country/language code, with '' being the default (English).

$.svg.graphing.regional['fr'] = {percentageText: 'Pourcentage'};
SVG Graph Renderers

Different graph types are rendered by plugin objects that are registered with the $.svg.graphing manager object above and may then be assigned to individual graphs. Each must implement the functions below. The standard chart types are:

SignatureReturnsComments
title() string Retrieve the display title for this chart type.

html += '<option value="' + id + '">' +
	chartType.title() + '</option>';
description() string Retrieve a longer description of this chart type.

$('#graphDesc').text(chartType.description());
options() string[] Retrieve a list of the options that may be set for this chart type. Each entry should have the format: 'name (type) - description'.

for (var i = 0; i < chartType.options().length; i++) { ... }
drawGraph(graph) null Actually draw the graph in this type's style. This function is called internally by the graph object in response to a redraw() call.

graph (object) is the SVGGraph object.

chartType.drawGraph(graph);

Chart Type Options

Chart TypeNameTypeDefaultComments
column
stackedColumn
barWidthnumber10 The width (pixels) of each column.
 barGapnumber10 The gap (pixels) between column.
row
stackedRow
barWidthnumber10 The width (pixels) of each row.
 barGapnumber10 The gap (pixels) between row.
pieexplodenumber or number[][] The indexes of series (starting at zero) to explode out from the main pie chart.

Since 1.4.2 - value may be a single number.
 explodeDistnumber10 The distance (pixels) that exploded series are moved.
 pieGapnumber10 The gap (pixels) between pie charts if multiple values are graphed.
SVG Graph Series

The series object, SVGGraphSeries, contains details about a series in the graph. Add a new series with svg.graph.addSeries(), or retrieve the existing series with svg.graph.series().

end | format | name | SVGGraphSeries | values

SignatureReturnsComments
SVGGraphSeries(graph, name, values, fill, stroke, strokeWidth, settings) SVGGraphSeries Create a new graph series. It is only used internally as part of the addSeries() call.

graph (SVGGraph) is the parent graph.

name (string, optional) is the name of this series.

values (number[]) is the list of values to be plotted.

fill (string) is how the series should be displayed.

stroke (string, optional) is the colour of the (out)line for the series.

strokeWidth (number, optional) is the width of the plotted lines.

settings (object, optional) is additional formatting settings.
end() graph object Finish with this series and return to the parent graph.

svg.graph.series(i).format(...).end()...;

Since 1.3.0.
format(fill, stroke, strokeWidth, settings) series object or object Set or retrieve the formatting for this series.

fill (string) is how the values are filled when plotted.

stroke (string, optional) is the (out)line colour.

strokeWidth (number, optional) is the line's width.

settings (object, optional) is additional formatting settings (SVG attributes) for the series.

series.format('lightyellow', 'yellow', {fillOpacity: 0.5});

If no parameters are provided, the function returns the current formatting settings as an object with at least fill, stroke, and strokeWidth attributes.

var format = series.format();
alert(format.fill);
name(name) series object or string Set or retrieve the name for this series.

name (string) is the series' name.

series.name('Opera');

If no parameters are provided, the function returns the current name.

var name = series.name();
values(name, values) series object or number[] Set or retrieve the values for this series.

name (string, optional) is the series' name.

values (number[]) is the values to be graphed.

series.values([0.2, 0.3, 0.3, 0.4]);

If no parameters are provided, the function returns the current values.

var values = series.values();

Internally the following fields are available for graph renderers.

NameTypeComments
_axis number Which axis (1 or 2) does this series apply to?
_fill string How the series is rendered.
_name string The name of the series.
_settings object Additional formatting settings for the series.
_stroke string The (out)line colour.
_strokeWidth number The line width.
_values number[] The list of values for the series.
SVG Graph Axis

The axis object, SVGGraphAxis, contains details about an axis on the graph. The graph maintains several references to axes: xAxis, yAxis, x2Axis, y2Axis, and _getPercentageAxis().

end | labels | line | scale | SVGGraphAxis | ticks | title

SignatureReturnsComments
SVGGraphAxis(graph, title, min, max, major, minor) SVGGraphAxis Create a new graph axis. It is only used internally as part of the graph initialisation.

graph (SVGGraph) is the parent graph.

title (string) is the title of the axis.

min (number) is the minimum value displayed on this axis.

max (number) is the maximum value displayed on this axis.

major (number) is the distance between major ticks.

minor (number, optional) is the distance between minor ticks.
end() graph object Finish with this axis and return to the parent graph.

svg.graph.xAxis.labels(...).end()...;

Since 1.3.0.
labels(labels, colour, format) axis object or object Set or retrieve the labels for this axis.

labels (string[]) is the text for each entry.

colour (string, optional) is the fill colour for the labels.

format (object, optional) is formatting (SVG attributes) settings for the labels.

svg.graph.xAxis.labels(
	['2002', '2004', '2005', '2006'], 'blue');

If no parameters are provided, the function returns the current labels settings as an object with labels and format attributes (colour appears in format as fill).

var labelSettings = svg.graph.xAxis.labels();
alert(labelSettings.labels);

Since 1.4.2 - added colour.
line(colour, width, settings) axis object or object Set or retrieve the line formatting for this axis.

colour (string) is the line's colour.

width (number, optional) is the line's width.

settings (object, optional) is additional formatting settings (SVG attributes) for the line.

svg.graph.xAxis.line('gray', 2, {strokeDashArray: '3,2'});

If no parameters are provided, the function returns the current line settings as an object with stroke and strokeWidth attributes.

var lineFormat = svg.graph.xAxis.line();
alert(lineFormat.stroke);
scale(min, max) axis object or object Set or retrieve the scale for this axis.

min (number) is the minimum value shown.

max (number) is the maximum value shown.

svg.graph.yAxis.scale(-5, 105);

If no parameters are provided, the function returns the current scale as an object with min and max attributes.

var scale = svg.graph.yAxis.scale();
alert(scale.min + ' - ' + scale.max);
ticks(major, minor, size, position) axis object or object Set or retrieve the ticks for this axis.

major (number) is the distance between major ticks.

minor (number) is the distance between minor ticks.

size (number, optional) is the length of the major ticks (default is 10, minor ticks are half size).

position (string, optional) is the location of the ticks: 'in', 'out' (default), 'both'.

svg.graph.yAxis.ticks(10, 5);

If no parameters are provided, the function returns the current ticks settings as an object with major, minor, size, and position attributes.

var ticks = svg.graph.yAxis.ticks();
alert(ticks.major);
title(title, offset, colour, format) axis object or object Set or retrieve the title for this axis.

title (string) is the title text.

offset (number, optional) is the distance to offset the title position.

colour (string, optional) is the fill colour for the title.

format (object, optional) is formatting settings (SVG attributes) for the title.

svg.graph.xAxis.title('Year', 'green', {stroke: 'black'});

If no parameters are provided, the function returns the current title settings as an object with title, offset, and format attributes (colour appears in format as fill).

var titleSettings = svg.graph.xAxis.title();
alert(titleSettings.title);

Since 1.4.2 - added colour.

Internally the follow fields are available for graph renderers.

NameTypeComments
_labels string[] The list of labels for the axis - one per possible value across all series.
_labelFormat object Formatting settings for the labels.
_lineFormat object Formatting settings for the axis lines, including tick marks.
_scale object Scale settings: min and max attributes.
_ticks object Tick mark options: major, minor, size, and position attributes.
_title string The title of the axis.
_titleFormat object Formatting settings for the title.
_titleOffset number The offset for positioning the title.
SVG Graph Legend

The legend object, SVGGraphLegend, contains details about the legend for the graph. Access the legend via svg.graph.legend.

area | end | settings | show | SVGGraphLegend

SignatureReturnsComments
SVGGraphLegend(graph, bgSettings, textSettings) SVGGraphLegend Create a new graph legend. It is only used internally as part of the graph initialisation.

graph (SVGGraph) is the parent graph.

bgSettings (object, optional) is additional formatting settings for the legend background.

textSettings (object, optional) is additional formatting settings for the legend text.
area(left, top, right, bottom) legend object or number[4] Set or retrieve the legend area. If the parameter value is less than or equal to 1 it is taken as the proportion of the width/height. If more than 1 it is the number of pixels.

left (number) is the left position or (number[4]) all the positions in an array.

top (number) is the top position (omitted if left is an array).

right (number) is the right position (omitted if left is an array).

bottom (number) is the bottom position (omitted if left is an array).

svg.graph.legend.area(
	[0.005, 0.1, 0.125, 0.5]);

If no parameters are provided, the function returns the current area.

var area = svg.graph.legend.area();
alert(area[0] + ',' + area[1]);
end() graph object Finish with this legend and return to the parent graph.

svg.graph.legend.settings(...).end()...;

Since 1.3.0.
settings(sampleSize, bgSettings, textSettings) legend object or object Set or retrieve additional settings for the legend area.

sampleSize (number, optional) the size of the sample box to display.

bgSettings (object) is additional formatting settings (SVG attributes) for the legend background.

textSettings (object, optional) is additional formatting settings (SVG attributes) for the legend text.

svg.graph.legend.settings(
	{fill: 'lightgoldenrodyellow',
	stroke: 'gray'});

If no parameters are provided, the function returns the current settings as an object with sampleSize, bgSettings, and textSettings attributes.

var settings =
	svg.graph.legend.settings();
alert(settings.sampleSize);
show(show) legend object or boolean Set or retrieve whether the legend should be shown.

show (boolean) is true to display it, false to hide it.

svg.graph.legend.show(true);

If no parameters are provided, the function returns the current visibility.

var visible = svg.graph.legend.show();

Internally the follow fields are available for graph renderers.

NameTypeComments
_area number[4] The legend area: left, top, right, bottom.
_bgSettings object Additional formatting settings for the legend background.
_sampleSize number The size of the same box to display. Default is 15.
_show boolean Show the legend?
_textSettings object Additional formatting settings for the legend text.