A jQueryplugin
that sets a division to request a Google chart.
The current version is 2.0.0 and is available
under the MIT licence.
For more detail see the documentation reference page.
Or see a minimal page that you could
use as a basis for your own investigations.
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.
You can override the defaults globally as shown below:
$.gchart.setDefaults({legend: 'right'});
Processed fields are marked with a class of is-gchart
and are not re-processed if targeted 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.
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.
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.
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 (candlestick) 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.
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, or make the entire chart
fully or partially transparent.
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 stripes.
In addition you can set the minimum margins around the chart and the minimum legend size.
Specify a legend for your chart (legend), along with its
label order (legendOrder), colour (legendColor),
and font size (legendSize).
See the Backgrounds tab to change the dimensions of the legend.
Control the sizing and spacing of the bars on your bar charts, along with their backgrounds.
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.
Use the $.gchart.gradient or $.gchart.stripe
functions to style the bar backgrounds.
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.
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.
You can also set the fill to only appear for a range of values.
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.
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),
line colour (color), displayed text (labels),
their positions (positions) and styling (style),
the range of values shown (range), what is drawn (drawing),
and/or the format of the labels (format).
The axes are named 'top', 'left' or 'y', 'bottom' or 'x', and 'right'.
Axes:TopBottom
LeftRight
Second leftSecond 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('??', 'blue'),
$.gchart.axis('??', ['0', '50', '100'], 'blue'),
$.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'),
$.gchart.axis('??').format($.gchart.formatFloat, '', 'K', 1, false, true)];
$('#axesApply').click(function() {
var newAxes = [];
$.each(['Top', 'Bottom', 'Left', 'Right', 'Left2', 'Right2'],
function(i, name) {
var axis = demoAxes[$('#axes' + name).val()];
if (axis) {
newAxes.push(typeof axis == 'string' ? name.toLowerCase() :
$.extend({}, axis.axis(name.toLowerCase())));
}
});
$('#axesChart').gchart('option', {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:FirstSecond
$('#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('option', {ranges: newRanges});
}).click();
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),
priority with respect to other chart elements (priority),
alignment with respect to the line/bar (placement),
and offsets from the normal position (offsets).
You can use the $.gchart.marker function
to assist in creating marker definitions.
Specify
dynamic icons in your chart with the icons
option, which is an array of objects describing each icon.
You need to add the jquery.gchart.icons.js module to your page.
You can add as many icons as you want.
Each icon object has attributes for icon name (name), configuration data
(data), index of the series to which it applies (series),
item in the series (item, 'all' for all), z-index (zIndex),
position (position), and offsets (offsets).
You can use any of the $.gchart.icon, $.gchart.bubbleIcon,
$.gchart.mapPinIcon, $.gchart.noteIcon,
$.gchart.weatherIcon, $.gchart.outlineIcon,
$.gchart.colorVaryIcon, $.gchart.sizeVaryIcon,
$.gchart.colorSizeVaryIcon, $.gchart.stackingIcon,
$.gchart.stackingColorVaryIcon, or $.gchart.embeddedChart
functions to assist in creating icon definitions.
You can create other chart types as well.
You need to add the jquery.gchart.ext.js module to your page for these.
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).
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.
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).
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));
You can also create a
mathematical formula via Google Charts. The formula must be specified
using the TeX notation.
And now you can display
graphs and networks via Google Charts. The graph layout must be specified
using the DOT language
or as a JavaScript structure via the graphviz function.
You need to add the jquery.gchart.graphviz.js module to your page
instead of jquery.gchart.ext.js for this type of chart.
Google charting allows you to colour maps based on data.
You need to add the jquery.gchart.ext.js module to your page for this.
For a
map, use the $.gchart.map helper function.
It expects 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,
to identify the regions, optionally followed by a dash and a second identifier
for regions and cities.
The map zooms to show all of the selected areas by default. In addition you can
specify extra (pixel) spacing around the map (left/right/top/bottom) to
zoom out or the bottom/left/top/right latitudes and longitudes to show.
The original map implementation is still available.
Under this scheme you must select a region of the world to view
and can only use country codes for selecting areas on the map.
Google charting also lets you retrieve a JSON description of the chart, allowing you
to add imagemap-like capabilities to your chart, for example on mouse hover.
You obtain this data by setting provideJSON to true
and adding an onLoad handler.
The built-in findRegion function converts a mouse position over the
chart into the corresponding region from the JSON data.
The normal access to a Google chart is via a GET URL, which is limited to 2K in size.
If you need to show more data you can use a POST URL, allowing up to 16K in size,
by setting usePost to true.
Note that the resulting chart appears within an iframe.
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('option', {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.
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.
This tab highlights examples of this plugin in use "in the wild".
None as yet.
To add another example, please contact me (wood.keith{at}optusnet.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
format: 'png', // Returned format: png, gif
usePost: false, // True to POST instead of GET - for larger charts with more data
secure: false, // True to access a secure version of Google Charts
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
opacity: 0, // Make the entire chart semi-transparent (0.0-1.0 or 0-100)
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
legendOrder: 'normal', // The order of items within a legend: normal, reverse, automatic
legendDims: null, // The minimum size (pixels) of the legend: [width, height]
legendColor: '', // The colour of the legend
legendSize: 0, // The font size of the legend
type: 'pie3D', // Type of chart requested: line, lineXY, sparkline, barHoriz, barVert,
// barHorizGrouped, barVertGrouped, barHorizOverlapped, barVertOverlapped, pie,
// pie3D (default), pieConcentric, radar, radarCurved, venn, scatter, map,
// mapOriginal, meter, qrCode, formula, graphviz
encoding: '', // Type of data encoding: text (default), scaled, simple, extended
series: [$.gchart.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
functions: [], // Functions to apply to be plotted based on data
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),
// placement (string or string[]), offsets (number[2])
icons: [], // Definitions of dynamic icons for the chart, each entry is an object with
// name (string), data (string), series (number), item (number), zIndex (number),
// position (number[2]), offsets (number[2])
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: null, // The x and y spacings between grid lines (number or number[2])
gridLine: null, // The line and gap lengths for the grid lines (number or number[2])
gridOffsets: null, // The x and y offsets for the grid lines (number or number[2])
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 -------------------
mapLatLong: false, // True to use lat/long coords in mapArea
mapArea: null, // New maps: (number) pixel border all around or
// (number[4]) individual pixel borders or lat/long
// Original maps: the general area to show:
// world, africa, asia, europe, middle_east, south_america, usa
mapRegions: [], // List of country/state codes to plot
mapDefaultColor: 'bebebe', // The colour for non-plotted countries/states
mapColors: ['blue', 'red'], // 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
// Callback
onLoad: null, // Function to call when loaded
provideJSON: false // True to return JSON description of chart with the onLoad callback
});
$.gchart.setDefaults(options) // Set defaults for all instances
$(selector).gchart('option', options) // Update the chart settings
$(selector).gchart('option', name, value) // Update a chart setting
$(selector).gchart('option', name) // Retrieve a chart setting
$(selector).gchart('destroy') // Remove the chart functionality
$.gchart.axis(axis, lineColour, labels, positions, rangeStart, rangeEnd, rangeInterval,
colour, alignment, size, format) // Generate an axis definition
$.gchart.color(r, g, b, a) // Convert a colour
$.gchart.gradient(angle, colour1, colour2) // Generate a gradient definition
$.gchart.gradient(angle, colours, positions) // Generate a gradient definition
$.gchart.stripe(angle, colours, widths) // Generate a stripe definition
$.gchart.range(vertical, colour, start, end) // Generate a range definition
$.gchart.marker(shape, colour, series, item, size, priority, text,
positioned, placement, offsets) // Generate a marker definition
// Generate a number format definition
$.gchart.numberFormat(type, prefix, suffix, precision, showX, zeroes, separators)
$.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.fn(series, data, start, end, step, fnText) // Generate a data function definition
$.gchart.fnVar(name, start, end, step) // Generate a data function variable definition
$.gchart.findRegion(event, jsonData) // Determine the region within a chart
// From jquery.gchart.ext.js
// Generate the options for a map
$.gchart.map(latLongArea, mapArea, values, defaultColour, colour, endColour, options)
// Generate the options for a Google meter
$.gchart.meter(text, values, maxValue, colours, labels, styles, options)
// Generate the options for a QR Code
$.gchart.qrCode(text, encoding, ecLevel, margin)
$.gchart.scatter(values, minMax, labels, colours, options) // Generate series for a scatter chart
$.gchart.venn(size1, size2, size3, overlap12, overlap13, overlap23, overlap123,
options) // Generate the options for a Venn diagram
// From jquery.gchart.graphviz.js
// Generate options for a GraphViz chart
$.gchart.graphviz(engine, options, directed, nodes, edges, attrs)
// From jquery.gchart.icons.js
// Generate dynamic icons
$.gchart.icon(name, data, series, item, zIndex, position, offsets)
$.gchart.bubbleIcon(text, image, tail, large, shadow, bgColour, colour,
series, item, zIndex, position, offsets)
$.gchart.mapPinIcon(letter, image, style, shadow, bgColour, colour,
series, item, zIndex, position, offsets)
$.gchart.noteIcon(title, text, type, large, alignment, colour,
series, item, zIndex, position, offsets)
$.gchart.weatherIcon(title, text, type, image,
series, item, zIndex, position, offsets)
$.gchart.outlineIcon(text, size, bold, alignment, colour, outline,
series, item, zIndex, position, offsets)
$.gchart.colourVaryIcon(image, colourSeries, colourLow, colourMiddle, colourHigh,
size, outline, alignment, series, item, zIndex, position, offsets)
$.gchart.sizeVaryIcon(image, sizeSeries, zeroSize, sizeMultiplier, minSize, colour,
outline, alignment, series, item, zIndex, position, offsets)
$.gchart.colourSizeVaryIcon(image, colourSeries, colourLow, colourMiddle,
colourHigh, sizeSeries, zeroSize, sizeMultiplier, minSize, outline,
alignment, series, item, zIndex, position, offsets)
$.gchart.stackingIcon(image, repeatSeries, scalingFactor, horizontal, size, colour,
outline, spacing, alignment, series, item, zIndex, position, offsets)
$.gchart.stackingColourVaryIcon(image, repeatSeries, scalingFactor, horizontal,
size, colourSeries, colourLow, colourMiddle, colourHigh, outline,
spacing, alignment, series, item, zIndex, position, offsets)
$.gchart.embeddedChart(embeddedOptions, bubble, alignment, padding, frameColour,
fillColour, series, item, zIndex, position, offsets)
Usage
Include the jQuery library (1.7+) in the head section of your page.
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 wood.keith{at}optusnet.com.au
with comments or suggestions.