jQuery Google Charting

A jQuery plugin that sets a division to request a Google chart. If you find this plugin useful please vote for it on the jQuery site.

The current version is 1.2.3 and is available under the GPL and MIT licences. For more detail see the documentation reference page. Or see a minimal page that you could use as a basis for your own investigations.

Default Settings

The Google Chart functionality can easily be added to a division with appropriate default settings. Google Chart generates a chart as an image in response to a HTTP request with parameters defining the content and appearance. This plugin hides all of that behind a JavaScript interface.

You can also remove the charting functionality with the 'destroy' command if it is no longer required.

Basic chart:

$('#defaultChart').gchart();

$('#removeChart').toggle(function() {
		$(this).text('Re-attach');
		$('#defaultChart').gchart('destroy');
	},
	function() {
		$(this).text('Remove');
		$('#defaultChart').gchart();
	}
);

You can override the defaults globally as shown below:

$.gchart.setDefaults({legend: 'right'});

Processed fields are marked with a class of hasGChart and are not re-processed if targetted a second time.

Complete Example

This chart shows some of the capabilities of the Google chart API. It depicts average minimum and maximum temperatures and rainfall for Brisbane, Australia.

The individual elements of the charts are demonstrated in more detail on the other tabs.

Brisbane weather:

$('#brisChart').gchart({type: 'line', maxValue: 40,
	title: 'Weather for|Brisbane, Australia', titleColor: 'green',
	backgroundColor: $.gchart.gradient('horizontal', 'ccffff', 'ccffff00'),
	series: [$.gchart.series('Max', [29.1, 28.9, 28.1, 26.3,
		23.5, 21.2, 20.6, 21.7, 23.8, 25.6, 27.3, 28.6], 'red', 'ffcccc'),
		$.gchart.series('Min', [20.9, 20.8, 19.5, 16.9,
		13.8, 10.9, 9.5, 10.0, 12.5, 15.6, 18.0, 19.8], 'green'),
		$.gchart.series('Rainfall', [157.7, 174.6, 138.5, 90.4,
		98.8, 71.2, 62.6, 42.7, 34.9, 94.4, 96.5, 126.2], 'blue', 0, 200)],
	axes: [$.gchart.axis('bottom', ['Jan', 'Feb', 'Mar', 'Apr',
		'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 'black'),
		$.gchart.axis('left', 0, 40, 'red', 'right'),
		$.gchart.axis('left', ['C'], [50], 'red', 'right'),
		$.gchart.axis('right', 0, 200, 50, 'blue', 'left'),
		$.gchart.axis('right', ['mm'], [50], 'blue', 'left')],
	legend: 'right'
});

Chart Types

Google charting provides for a number of different chart styles. Common chart types are shown below.

Chart types:   Show legend

$('#typedChart').gchart({type: 'line',
	dataLabels: ['2002', '2004', '2005', '2006'], legend: 'right',
	series: [$.gchart.series('IE', [95.97, 91.80, 88.16, 86.64], 'red'),
		$.gchart.series('Netscape', [3.39, 2.83, 1.61, 0.00], 'green'),
		$.gchart.series('Firefox', [0.00, 4.06, 8.13, 9.95], 'blue')]
});

$('#selectType,#showLegend').change(function() {
	$('#typedChart').gchart('change', {type: $('#selectType').val(),
		legend: $('#showLegend').val()});
});

Pie charts only plot a single set of values, unless you choose the pieConcentric chart type. To customise colours for the segments, you need to supply them as an array of colours for each series. If fewer colours than the number of segments are given, the colours are recycled for the remaining segments.

Pie charts:    

 

  Orientation

var data = [$.gchart.series('2004', [91.80, 2.83, 4.06]),
	$.gchart.series('2005', [88.16, 1.61, 8.13])];
		
$('#pieChart').gchart({type: 'pie', series: data,
	dataLabels: ['IE', 'Netscape', 'Firefox']});

$('input[name=pieType],#pieColours,#pieAngle').change(function() {
	data[0].color = ($('#pieColours').is(':checked') ?
		['red', 'lime', 'blue'] : null);
	data[1].color = ($('#pieColours').is(':checked') ?
		['ff8888', '88ff88', '8888ff'] : null);
	$('#pieChart').gchart('change',
		{type: $('input[name=pieType]:checked').val(),
		series: data, pieOrientation: $('#pieAngle').val()});
});

For a line chart you can also explicitly set the x- and y-coordinates, rather than using the even x-spacing that is the default. Use the $.gchart.seriesForXYLines helper function to create the series. It expects an array of series, as before, however each value consists of the point's x- and y-coordinate as an array. If you want to use the default even spacing for one of the series, provide just the y-values.

X-Y line charts:

$('#lineXYChart').gchart({type: 'lineXY', series: $.gchart.seriesForXYLines(
	[$.gchart.series([[0, 20], [30, 30], [60, 40], [70, 50],
	[90, 60], [95, 70], [100, 80]], 'red'),
	$.gchart.series([[10, 100], [30, 90], [40, 40], [45,20],
	[52, 10]], 'green'),
	$.gchart.series([5, 33, 50, 55, 7], 'blue')])});

For a financial chart you need to specify at least four series. You then designate one series to use as the basis for the financial markers. This series defines the bottom of the vertical line. The following two series specify the bottom and top of the rectangle respectively. Finally, the top of the vertical line comes from the third following series.

You can also include other series that are graphed normally. Use the visibleSeries setting to indicate which series are directly displayed and which are reserved for the markers.

Financial charts:

$('#financialChart').gchart({type: 'line',
	encoding: 'scaled', visibleSeries: 1,
	series: [$.gchart.series([20, 10, 15, 25, 17, 30], 'yellow'),
	$.gchart.series([0, 5, 10, 7, 12, 6], -50, 100),
	$.gchart.series([35, 25, 45, 47, 24, 46], -50, 100),
	$.gchart.series([15, 40, 30, 27, 39, 54], -50, 100),
	$.gchart.series([70, 55, 63, 59, 80, 60], -50, 100)],
	markers: [$.gchart.marker('financial', '', 1, [1, 4], 20)]});

Backgrounds and Margins

Change the background colour of the chart and/or the entire image. You can even make these fully or partially transparent to allow a background image to show through.

You can also create gradients of colour for your backgrounds by specifying its angle with respect to the positive x-axis (either as a named value or in degrees) and the colours to merge between.

Make use of the helper functions, $.gchart.gradient and $.gchart.stripe, for simple gradients and equal stripes.

In addition you can set the minimum margins around the chart and the minimum legend size.

Backgrounds: All

  Chart

Margins: Left Right  

  Top Bottom  

Legend: Width Height  

 

$('#backgroundChart').gchart({type: 'line',
	maxValue: 61, encoding: 'simple',
	backgroundColor: 'ffffaa', chartColor: 'ffffaa',
	dataLabels: ['0', '5', '10'], legend: 'right',
	series: [$.gchart.series('Level', [28, 4, 0, 4, 11, 5, 9,
	7, 7, 7, 10, 20, 35, 46, 61, 46, 46, 23, 20, 28])]});

// These are the values you would use for your backgrounds
var demoBackgrounds = ['ffffaa',
	'transparent',
	'ffcccc80',
	$.gchart.gradient('horizontal', 'black', 'transparent'),
	$.gchart.gradient('diagonalUp', 'lime', 'blue'),
	{angle: 'diagonalDown', colorPoints:
		[['yellow', 0.2], ['ff000000', 0.8]]},
	{angle: 'vertical', colorPoints: [['red', 0], ['white', 1]]},
	{angle: 60, colorPoints: [['white', 0.3], ['blue', 0.7]]},
	$.gchart.gradient(0, ['white', 'yellow', 'red']),
	$.gchart.stripe('horizontal',
		['white', 'silver', 'gray', 'white', 'silver']),
	{angle: 30, striped: true, colorPoints:
		[['white', 0.25], ['silver', 0.5], ['white', 0.25]]}];

$('#bgApply').click(function() {
	$('#backgroundChart').gchart('change', {
		backgroundColor: demoBackgrounds[$('#bgAll').val()],
		chartColor: demoBackgrounds[$('#bgChart').val()],
		margins: [getValue('#marginLeft'), getValue('#marginRight'),
		getValue('#marginTop'), getValue('#marginBottom')],
		legendSize: [getValue('#legendWidth'), getValue('#legendHeight')]});
});

Chart Title

Specify a title for your chart (title), along with its colour (titleColor) and size (titleSize). Use a pipe (|) in the title for a new line.

Titles: Text 

  Colour Size  

 

$('#titleChart').gchart({type: 'line', maxValue: 61, encoding: 'simple',
	title: 'My Chart', titleColor: 'blue', titleSize: 20,
	series: [$.gchart.series('Level', [28, 4, 0, 4, 11, 5, 9,
	7, 7, 7, 10, 20, 35, 46, 61, 46, 46, 23, 20, 28])]});

$('#titleApply').click(function() {
	$('#titleChart').gchart('change', {
		title: $('#titleText').val(), titleColor: $('#titleColour').val(),
		titleSize: parseFloat($('#titleSize').val())});
});

Bar Chart Sizing and Spacing

Control the sizing and spacing of the bars on your bar charts. Set the width of the bars (barWidth), the spacing between bars within a group (barSpacing), and the gap between groups of bars (barGroupSpacing). Note that if the width is set to relative, the spacing values should be between 0.0 and 1.0.

You can also set the zero point of a bar chart (barZeroPoint). This value, from 0.0 at the bottom/left to 1.0 at the top/right, indicates the starting position for the bars, which then extend from here up/down/left/right to the actual value.

Bar sizing:

  Spacing Group spacing  

  Zero point  

   

 

$('#barChart').gchart({type: 'barVertGrouped',
	barWidth: 20, barSpacing: 5, barGroupSpacing: 8, barZeroPoint: 0.0,
	series: [$.gchart.series('IE', [95.97, 91.80, 88.16, 86.64], 'red'),
		$.gchart.series('Netscape', [3.39, 2.83, 1.61, 0.00], 'green'),
		$.gchart.series('Firefox', [0.00, 4.06, 8.13, 9.95], 'blue')]
});

$('#barApply').click(function() {
	var type = 'bar' + ($('#barHoriz').is(':checked') ? 'Horiz' : 'Vert') +
		($('#barGrouped').is(':checked') ? 'Grouped' : '');
	var width = $('input[name=barWidthType]:checked').val();
	width = (width == 'w' ? getValue('#barWidth') : width);
	$('#barChart').gchart('change', {type: type,
		barWidth: width, barSpacing: getValue('#barSpacing'),
		barGroupSpacing: getValue('#barGroupSpacing'),
		barZeroPoint: getValue('#barZeroPoint')});
});

Line Appearance

Control the appearance of the lines depicting your data by setting its thickness and the length of the line segments and the gaps between them. A continuous line has a gap of zero. Each line (series) can have a different style.

Line appearance: Line Thickness  

  Dash length Gap length  

 

var lineSeries = [$.gchart.series([28, 4, 0, 4, 11, 5, 9, 7, 7, 7,
	10, 20, 35, 46, 61, 46, 46, 23, 20, 28], 'red', 5, [5, 5]),
	$.gchart.series([5, 8, 22, 24, 25, 10, 9, 23, 2, 3,
	5, 10, 37, 49, 56, 41, 15, 18, 20, 20], 'green', 3, [10, 2]),
	$.gchart.series([43, 50, 52, 54, 35, 10, 24, 33, 32, 43,
	45, 55, 60, 39, 36, 31, 25, 28, 33, 40], 'blue', 1, [1, 0])];

$('#lineChart').gchart({type: 'line', maxValue: 61, series: lineSeries});

$('#lineNumber').change(function() {
	var i = $(this).val();
	$('#lineThickness').val(lineSeries[i].lineThickness);
	$('#lineLength').val(lineSeries[i].lineSegments[0]);
	$('#lineGap').val(lineSeries[i].lineSegments[1]);
});

$('#lineApply').click(function() {
	$.extend(lineSeries[$('#lineNumber').val()],
		{lineThickness: getValue('#lineThickness'),
		lineSegments: [getValue('#lineLength'), getValue('#lineGap')]});
	$('#lineChart').gchart('change', {series: lineSeries});
});

Area Fills

Fill in the spaces between lines with colours. Each line (series) can have a different colour.

After creating your series, use its fillColor attribute to customise its appearance. This colour applies to the area between the current line and the next in the series. To fill the space at the top and bottom, add extra series for the maximum and minimum values.

Fill appearance: Line Colour  

 

var fillSeries = [$.gchart.series([40, 40], 'black', 'ffffcc'),
	$.gchart.series('Max', [29.1, 28.9, 28.1,
	26.3, 23.5, 21.2, 20.6, 21.7, 23.8, 25.6, 27.3, 28.6], 'red', 'ffcccc'),
	$.gchart.series('Min', [20.9, 20.8, 19.5,
	16.9, 13.8, 10.9, 9.5, 10.0, 12.5, 15.6, 18.0, 19.8], 'blue', 'ccccff'),
	$.gchart.series([0, 0], 'black')];

$('#fillChart').gchart({type: 'line', maxValue: 40, series: fillSeries});

$('#fillNumber').change(function() {
	var i = $(this).val();
	$('#fillColour').val(fillSeries[i].fillColor);
});

$('#fillApply').click(function() {
	fillSeries[$('#fillNumber').val()].fillColor = $('#fillColour').val();
	$('#fillChart').gchart('change', {series: fillSeries});
});

Grid Lines

Add grid lines to your charts via the gridSize and gridLine options. The former specifies the x- and y-spacing between grid lines, while the latter provides the length of the line segments and the gaps between them. A continuous line has a gap of zero.

The grid lines may be offset from their normal positions by setting gridOffsets to contain the appropriate x and y values.

Grid appearance: X-spacing Y-spacing  

  Dash length Gap length  

  X-offset Y-offset  

 

$('#gridChart').gchart({type: 'line', maxValue: 61, encoding: 'simple',
	gridSize: [20, 50], gridLine: [5, 5],
	series: [$.gchart.series([28, 4, 0, 4, 11, 5, 9,
	7, 7, 7, 10, 20, 35, 46, 61, 46, 46, 23, 20, 28])]});

$('#gridApply').click(function() {
	var gridLine = [getValue('#gridLength'), getValue('#gridGap')];
	if (gridLine[0] == null || gridLine[1] == null) {
		gridLine = [];
	}
	var gridOffsets = [getValue('#gridXOffset'), getValue('#gridYOffset')];
	if (gridOffsets[0] == null || gridOffsets[1] == null) {
		gridOffsets = [];
	}
	$('#gridChart').gchart('change',
		{gridSize: [getValue('#gridX'), getValue('#gridY')],
		gridLine: gridLine, gridOffsets: gridOffsets});
});

Axes Labels

Provide labels for any of the chart axes with the axes option, which is an array of objects describing each axis. You can even have multiple sets of labels on the one axis.

Each axis object has attributes for placement (axis), displayed text (labels), their positions (positions) and/or the range of values shown (range). The axes are named 'top', 'left' or 'y', 'bottom' or 'x', and 'right'.

Axes: Top Bottom 

  Left Right 

  Second left Second right 

 

$('#axesChart').gchart({type: 'line', maxValue: 61, encoding: 'simple',
	axes: [],
	series: [$.gchart.series('Level', [28, 4, 0, 4, 11, 5, 9,
	7, 7, 7, 10, 20, 35, 46, 61, 46, 46, 23, 20, 28])]});

// These are the values you would use for your axes,
// ignoring null and replacing '??' with the axis name
var demoAxes = [null,
	'??',
	$.gchart.axis('??', ['0', '50', '100']),
	$.gchart.axis('??', ['2005', '2006', '2007', '2008']),
	$.gchart.axis('??', ['min', 'avg', 'max'], [10, 35, 70]),
	$.gchart.axis('??', [], [0, 10, 20, 40, 80]),
	$.gchart.axis('??', 100, 200),
	$.gchart.axis('??', 1000, 0, -200),
	$.gchart.axis('??', [], [250, 350, 450], 200, 500),
	$.gchart.axis('??').ticks('red', -100),
	$.gchart.axis('??').drawing('ticks')];

$('#axesApply').click(function() {
	var newAxes = [];
	$.each(['Top', 'Bottom', 'Left', 'Right', 'Left2', 'Right2'],
		function(i, name) {
			var axis = demoAxes[$('#axes' + name).val()];
			if (axis) {
				newAxes[newAxes.length] = (typeof axis == 'string' ?
					name.toLowerCase() : axis.axis(name.toLowerCase()));
			}
		});
	$('#axesChart').gchart('change', {axes: newAxes});
});

Value Ranges

Highlight ranges of values on the chart via the ranges option, which is an array of objects describing each range. You can draw any number of ranges on a chart and they are added in their order in the array, with later ones overlaying earlier ones.

Each range object has attributes for orientation (vertical), colour (color), and the range covered (start and end) between 0.0 and 1.0. Omit the end of the range for a simple line.

You can use the $.gchart.range function to assist in creating range definitions.

Ranges: First Second 

 

$('#rangesChart').gchart({type: 'line', maxValue: 61, encoding: 'simple',
	ranges: [],
	series: [$.gchart.series('Level', [28, 4, 0, 4, 11, 5, 9,
	7, 7, 7, 10, 20, 35, 46, 61, 46, 46, 23, 20, 28])]});

// These are the values you would use for your ranges, ignoring null
var demoRanges = [null,
	$.gchart.range('ccccff', 0.25, 0.75),
	{color: 'red', start: 0.1},
	$.gchart.range(true, 'ccffcc', 0.6, 0.8),
	{vertical: true, color: 'blue', start: 0.7}];

$('#rangesApply').click(function() {
	var newRanges = [];
	$.each([1, 2], function(i, name) {
		var range = demoRanges[$('#ranges' + name).val()];
		if (range) {
			newRanges[newRanges.length] = range;
		}
	});
	$('#rangesChart').gchart('change', {ranges: newRanges});
});

Point Markers

Specify a custom marker for each point in your chart with the markers option, which is an array of objects describing each marker. You can add as many markers as you want.

Each marker object has attributes for shape (shape), colour (color), index of the series to which it applies (series), item in the series (item, 'all' for all), size (size), and priority with respect to other chart elements (priority).

You can use the $.gchart.marker function to assist in creating marker definitions.

Markers: Red line Green line 

 

$('#markersChart').gchart({type: 'line', maxValue: 61, encoding: 'scaled',
	markers: [],
	series: [$.gchart.series([28, 4, 0, 4, 11, 5, 9,
	7, 7, 7, 10, 20, 35, 46, 61, 46, 46, 23, 20, 28], 'red'),
	$.gchart.series([5, 8, 22, 24, 25, 10, 9,
	23, 2, 3, 5, 10, 37, 49, 56, 41, 15, 18, 20, 20], 'green')]});

// These are the values you would use for your markers, ignoring null
var demoMarkers = [null,
	$.gchart.marker('diamond', 'red', 0),
	$.gchart.marker('circle', 'yellow', 0),
	{shape: 'cross', color: '0000ff80', series: 0,
		item: 6, size: 30, priority: 'behind'},
	{shape: 'plus', color: '800080', series: 0,
		item: 6, size: 20, priority: 'above'},
	$.gchart.marker('sparkline', 'ffff0080', 0, 'all', 6),
	$.gchart.marker('sparkfill', 'ccccff', 0),
	$.gchart.marker('text', 'black', 0, 14, 12, 'above', 'Note this'),
	$.gchart.marker('flag', 'red', 0, 7, 'Unusual'),
	$.gchart.marker('number', 'blue', 0, 4),
	$.gchart.marker('number', 'gray', 0, 'every2',
		$.gchart.numberFormat($.gchart.formatFloat, 1, false, true)),
	$.gchart.marker('text', 'silver', 0, [0.25, 0.5], 50,
		'behind', 'Watermark', true)];

$('#markersApply').click(function() {
	var newMarkers = [];
	$.each([1, 2], function(i, name) {
		var marker = demoMarkers[$('#markers' + name).val()];
		if (marker) {
			newMarkers.push($.extend({}, marker, {series: i}));
		}
	});
	$('#markersChart').gchart('change', {markers: newMarkers});
});

More Chart Types

You can create other chart types as well.

For a scatter chart, use the $.gchart.scatter helper function. It expects an array of arrays of two or three numbers. The first two numbers are the x- and y-coordinates of the point, and the optional third value is the size of the point (0-100, defaulting to 100).

Scatter diagram:

$('#scatterChart').gchart($.gchart.scatter(
	[[10, 80], [30, 40, 50], [60, 70, 25], [90, 20], [20, 10],
	[40, 90], [20, 50, 75], [50, 70, 75], [90, 30], [70, 50]]));

For a Venn diagram, use the $.gchart.venn helper function. It expects three values for the relative sizes of the circles, then three values for the percentage overlaps between them (1 to 2, 1 to 3, and 2 to 3), and a final value for the percentage overlap between all three.

Venn diagram:

$('#vennChart').gchart($.gchart.venn(100, 80, 60, 10, 30, 30, 10));

For a Google meter, use the $.gchart.meter helper function. It expects the label for the arrow, the arrow's position, and the maximum value for the range (defaulting to 100).

Google meter:

$('#meterChart').gchart($.gchart.meter('Speed', 70));

QR Codes are a popular type of two-dimensional barcode, also known as hardlinks or physical world hyperlinks, that can store text containing a hyperlink, contact information, telephone number, etc. The individual block size depends on the amount of data to be presented, along with the encoding and error correction level specified.

For a QR code, use the $.gchart.qrCode helper function. It expects the text to encode, followed (optionally) by the encoding scheme, error correction level, and margin.

QR Codes:

$('#qrCode1').gchart($.gchart.qrCode('This is a QR Code'));
$('#qrCode2').gchart($.gchart.qrCode(
	'This one contains a longer text message', 'ISO-8859-1', 'high', 2));

Maps

Google charting allows you to colour maps based on data.

For a map, use the $.gchart.map helper function. It expects the map area (selectable below) and an object that contains the country/state codes as attribute names with the corresponding values to be plotted. You can also optionally provide a default colour for regions not plotted, and a starting and ending colour for those regions that are. Use the appropriate ISO 3166 country codes or US state codes to identify the regions.

Maps:

$('#mapChart').gchart($.gchart.map('world',
	{AU: 20, BR: 40, CO: 60, EG: 80, FR: 100, IN: 0,
	JP: 20, PL: 40, SA: 60, TR: 80, US: 100, ZA: 0}));

$('#selectMap').change(function() {
	$('#mapChart').gchart('change', {mapArea: $(this).val()});
});

Live Feeds

Charts can be used to show live feeds of data by continually updating the series data displayed. A flicker-free update ensures smooth transitions.

Here a live feed is simulated by rotating the series values. An onLoad callback updates the range of months being shown.

"Live" feed:

 

var liveData = [$.gchart.series('Max', [29.1, 28.9, 28.1, 26.3,
	23.5, 21.2, 20.6, 21.7, 23.8, 25.6, 27.3, 28.6], 'red', 'ffcccc'),
	$.gchart.series('Min', [20.9, 20.8, 19.5, 16.9,
	13.8, 10.9, 9.5, 10.0, 12.5, 15.6, 18.0, 19.8], 'green')];
var liveAxis = $.gchart.axis('bottom', ['Jan', 'Feb', 'Mar', 'Apr',
	'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 'black');

$('#liveChart').gchart({type: 'line', maxValue: 40,
	series: liveData, axes: [liveAxis], legend: 'right',
	onLoad: showRange});
	
setInterval(liveUpdate, 1000);

// Cycle labels and data
function liveUpdate() {
	var rotate = function(arr) {
		var value = arr.shift();
		arr.push(value);
		return arr;
	};
	for (var i = 0; i < 2; i++) {
		liveData[i].data = rotate(liveData[i].data);
	}
	liveAxis.labels(rotate(liveAxis.labels()));
	$('#liveChart').gchart('change', {series: liveData, axes: [liveAxis]});
}

function showRange() {
	$('#liveRange').text('Showing ' + liveAxis.labels()[0] +
		' to ' + liveAxis.labels()[11]);
}

Data Encoding

Google charting provides for a number of different encoding schemes for the data values so as to reduce the size of the information passed in the request.

Text
Values are normalised to 0-100 and are presented in normal text with commas (,) separating values and pipes (|) separating series.
Scaled text
Values are not normalised and are presented in normal text with commas (,) separating values and pipes (|) separating series. Additional values specify the minimum and maximum for each series.
Simple
Values are normalised to 0-61 and are presented as one character (A-Za-z0-9) with no value separator and commas (,) separating series.
Extended
Values are normalised to 0-4095 and are presented as two characters (A-Za-z0-9-.) with no value separator and commas (,) separating series.

Encoding types:

Encoded data:

$('#encodedChart').gchart({type: 'barVertGrouped', encoding: 'text',
	dataLabels: ['2002', '2004', '2005', '2006'], legend: 'right',
	series: [$.gchart.series('IE', [95.97, 91.80, 88.16, 86.64], 'ff0000'),
		$.gchart.series('Netscape', [3.39, 2.83, 1.61, 0.00], '00ff00'),
		$.gchart.series('Firefox', [0.00, 4.06, 8.13, 9.95], '0000ff')]
});

$('#selectEncoding').change(function() {
	$('#encodedChart').gchart('change', {encoding: $(this).val()});
	$('#encodedData').text($.gchart['_' + $(this).val() + 'Encoding'].
		apply($.gchart, [$.data($('#encodedChart')[0], 'gChart')]));
});

Loading Data

Data for the series may be loaded from external sources either as XML or CSV (comma-separated values).

The XML structure is as follows, with all attributes except point/@y being optional. Use the point/@x attribute to specify an X-Y line point.

<data>
	<series label="" color="" fillColor="" minValue=""
		maxValue="" lineThickness="" lineSegments="">
		<point x="" y=""/>
		...
	</series>
	...
</data>

Load XML:

 

$('#xmlChart').gchart({type: 'barVertGrouped',
	dataLabels: ['2002', '2004', '2005', '2006'], legend: 'right'});
		
$('#xmlLoad').click(function() {
	$('#xmlChart').gchart('change',
		{series: $.gchart.seriesFromXml($('#xmlSource').val())});
});

The CSV format may have a header line to identify the columns. These should be labelled with the series attributes (label, color, fillColor, minValue, maxValue, lineThickness, lineSegmentLine, lineSegmentGap) or be of the form yn, where n is a sequential number, for the data values. If you want to specify x-y line values, include columns named xn before the corresponding y-values. If x-values are not required for one series, leave the fields blank on that line. If there is no header line, all entries are treated as data values.

Load CSV:

 

$('#csvChart').gchart({type: 'line',
	dataLabels: ['2002', '2004', '2005', '2006'], legend: 'right'});
	
$('#csvLoad').click(function() {
	$('#csvChart').gchart('change',
		{series: $.gchart.seriesFromCsv($('#csvSource').val())});
});

In the Wild

This tab highlights examples of this plugin in use "in the wild".

To add another example, please contact me (kbwood{at}iinet.com.au) and provide the plugin name, the URL of your site, its title, and a short description of its purpose and where/how the plugin is used.

Quick Reference

A full list of all possible settings is shown below. Note that not all would apply in all cases. For more detail see the documentation reference page.

$(selector).gchart({
	width: 0, // Width of the chart
	height: 0, // Height of the chart
	margins: null, // The minimum margins (pixels) around the chart:
		// all or [left/right, top/bottom] or [left, right, top, bottom]
	title: '', // The title of the chart
	titleColor: '', // The colour of the title
	titleSize: 0, // The font size of the title
	backgroundColor: null, // The background colour for the entire image
	chartColor: null, // The background colour for the chart area
	legend: '', // The location of the legend: top, topVertical,
		// bottom, bottomVertical, left, right, or '' for none
	legendSize: null, // The minimum size (pixels) of the legend: [width, height]
	type: 'pie3D', // Type of chart requested: line, lineXY, sparkline,
		// barHoriz, barVert, barHorizGrouped, barVertGrouped, pie, pie3D (default),
		// pieConcentric, venn, scatter, radar, radarCurved, map, meter, qrCode
	encoding: '', // Type of data encoding: text (default), scaled, simple, extended
	series: [this.series('Hello World', [60, 40])], // Details about the values to be plotted
	visibleSeries: 0, // The number of series that are directly displayed, 0 for all
	dataLabels: [], // Labels for the values across all the series
	axes: [], // Definitions for the various axes, each entry is either
		// a string of the axis name or a GChartAxis object
	ranges: [], // Definitions of ranges for the chart, each entry is an object with
		// vertical (boolean), color (string), start (number, 0-1),
		// and end (number, 0-1) attributes
	markers: [], // Definitions of markers for the chart, each entry is an object with
		// shape (arrow, circle, cross, diamond, down, flag, horizontal,
		// number, plus, sparkfill, sparkline, square, text, vertical),
		// color (string), series (number), item (number), size (number),
		// priority (number), text (string), positioned (boolean)
	minValue: 0, // The minimum value of the data, $.gchart.calculate to calculate from data
	maxValue: 100, // The maximum value of the data, $.gchart.calculate to calculate from data
	gridSize: [], // The x and y spacings between grid lines
	gridLine: [], // The line and gap lengths for the grid lines
	gridOffsets: [], // The x and y offsets for the grid lines
	extension: {}, // Any custom extensions to the Google chart parameters
	// Bar charts -------------
	barWidth: null, // The width of each bar (pixels) or 'a' for automatic or 'r' for relative
	barSpacing: null, // The space (pixels) between bars in a group
	barGroupSpacing: null, // The space (pixels) between groups of bars
	barZeroPoint: null, // The position (0.0 to 1.0) of the zero-line
	// Pie charts -------------
	pieOrientation: 0, // The angle (degrees) of orientation from the positive x-axis
	// Maps -------------------
	mapArea: 'world', // The general area to show: world,
		// africa, asia, europe, middle_east, south_america, usa
	mapRegions: [], // List of country/state codes to plot
	mapDefaultColor: 'white', // The colour for non-plotted countries/states
	mapColors: ['aaffaa', 'green'], // The colour range for plotted countries/states
	// QR Code ----------------
	qrECLevel: null, // Error correction level: low, medium, quarter, high
	qrMargin: null // Margin (squares) around QR code, default is 4
});

$.gchart.setDefaults(options) // Set defaults for all instances

$(selector).gchart('change', options) // Update the chart settings

$(selector).gchart('destroy') // Remove the chart functionality

$.gchart.map(mapArea, values, defaultColour, startColour, endColour,
	options) // Generate the options for a map
$.gchart.meter(text, value, maxValue, colours, options)
	// Generate the options for a meter
$.gchart.qrCode(text, encoding, ecLevel, margin)
	// Generate the options for a QR Code
$.gchart.venn(size1, size2, size3, overlap12, overlap13, overlap23, overlap123,
	options) // Generate the options for a Venn diagram

$.gchart.axis(axis, labels, positions, rangeStart, rangeEnd,
	rangeInterval, colour, alignment, size) // Generate an axis definition
$.gchart.color(r, g, b, a) // Convert a colour
$.gchart.gradient(angle, colour1, colour2) // Generate a gradient definition
$.gchart.marker(shape, colour, series, item, size, priority, text, positioned)
	// Generate a marker definition
$.gchart.numberFormat(type, prefix, suffix, precision, showX, zeroes, separators)
	// Generate a number format definition
$.gchart.range(vertical, colour, start, end) // Generate a range definition
$.gchart.scatter(values, options) // Generate series for a scatter chart
$.gchart.series(label, data, colour, fillColour,
	minValue, maxValue, thickness, segments) // Generate a series definition
$.gchart.seriesForXYLines( series) // Generate series for an X-Y line chart
$.gchart.seriesFromCsv(csv) // Generate series from CSV data
$.gchart.seriesFromXml(xml) // Generate series from XML data
$.gchart.stripe(angle, colours) // Generate a stripe definition

Usage

  1. Include the jQuery library in the head section of your page.
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  2. Download and include the jQuery Google Charting JavaScript in the head section of your page.
    <script type="text/javascript" src="jquery.gchart.js"></script>
    Alternately, you can use the packed version jquery.gchart.pack.js (14.6K vs 51.1K), or the minified version jquery.gchart.min.js (18.4K, 6.1K when zipped).
  3. Connect the Google charting functionality to your divisions.
    $(selector).gchart({series: [$.gchart.series([20, 50, 30])]});

For more detail see the documentation reference page. Or see a minimal page that you could use as a basis for your own investigations.

Comments

I've been developing some internal web apps for my team ... to display log statistics and whatnot, and jQuery and gCharts have become an integral component. So kudos to you. gChart is well made and I am a fan.

Steven Rosenshine

Thanks a lot for the really easy to use and useful plugin. It works like a charm.

Siddhartha Azad

Your jQuery Google Chart plugin is great, thank you for making this available for use. I'm really impressed with your work.

Don Yash

Just a quick note to say thanks...that plugin is unreal! Very powerful, yet so simple.

Gary (Canada)

Thanks for the great plugin. It's made interacting with the Google Charting API so much easier than building the URLs myself.

Dan Turkenkopf

Contact Keith Wood at kbwood{at}iinet.com.au with comments or suggestions.

Change History

VersionDateChanges
1.2.315 Aug 2009
  • Added onLoad setting
1.2.220 Jun 2009
  • Corrected missing colours for series
  • Corrected error with title size when no title colour
1.2.104 Apr 2009
  • Ensure width and height are not zero
  • Apply flicker-free chart updates (thanks to Andrew Collins)
1.2.007 Feb 2009
  • Added margins and legendSize settings
  • Added item colours per series
  • Added visibleSeries setting
  • Added $.gchart.barWidthAuto and $.gchart.barWidthRelative for bar widths
  • Added pieOrientation setting
  • Added topVertical and bottomVertical values for legend setting
  • Added gridOffsets setting
  • Added range interval to axis function
  • Added GChartAxis object and support for drawing control, and tick mark colour and length
  • Added flag, financial, and number types for markers
  • Added every n and absolute positioning for markers
  • Added numberFormat function to prepare number format definitions
  • Corrected encoding of labels for other languages
  • Correct 0 item index for markers
  • Simple pie charts no longer accept multiple series to customise labels and colours
1.1.129 Nov 2008
  • Corrected encoding of labels
1.1.008 Nov 2008
  • Added sparkfill and sparkline marker types
  • Deprecated lineXYSeries function in favour of seriesForXYLines
  • Added seriesFromXml and seriesFromCsv functions for loading external data
  • Google chart URLs now generated as XHTML-compliant
1.0.004 Oct 2008
  • Initial release