RGraph is a JavaScript charts library based on
HTML5 SVG and canvas. RGraph is mature (over 17 years
old) and has a wealth of features making it an ideal
choice to use for showing charts on your website.
In the April 2025 release a new datagrid object
was added.
This makes it easy to add static or dynamic data
tables to your pages. It can be used whether you use the
canvas or SVG libraries or entirely standalone.
Get the latest version of RGraph (version 6.22, 24th June 2025) from
the download page. You can read the changelog here. There's also older versions available,
minified files and links to cdnjs.com hosted libraries.
Working with RGraph objects is purposefully easy, to make them
straightforward to integrate into your own scripts if you want
to. For any
particular chart type, there are a few files required - the common
libraries and the chart-specific library. Eg:
RGraph.common.core.js is a function library that contains a large set of functions that
support the chart classes.
Some functions, and sets of functions, have their own files. For example,
the Google Sheets functionality resides in RGraph.common.sheets.js,
so if you don't need this facility, you don't need this file.
Each of the chart libraries (RGraph.*.js) contains that particular
charts class. If you'd like to see a "bare-bones"
implementation, you can look at the basic examples that are
included in the download archive.
Canvas and context references
Each chart object maintains references to the context and canvas
as properties. So to get hold of them all you need to do is this:
<script>
// 1/2 First draw the chart
bar = new RGraph.Bar({
id: 'cvs',
data: [1,5,8,4,6,3,1,5,7,8,4,6],
options: {
xaxisLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
}
}).draw()
// 2/2 Now get hold of the references
context = bar.context; // Get hold of a reference to the context
canvas = bar.canvas; // Get hold of a reference to the canvas
</script>
Paths in the RGraph libraries
For speed and convenience - RGraph uses a custom path function to facilitate path
drawing.
If you look through the RGraph source code you might see the RGraph.path
function in use or calls to this.path .
This function makes the canvas path syntax, which is quite verbose,
much less so. As an example:
RGraph.path({
object: this,
path: 'b r % % % % s % f %',
args: [5, 5, 100, 100, 'black', 'red']
});
this.path(
'b r % % % % s % f %',
5,5,100,100,
'black','red'
);
This is a shorter and clearer way of doing a beginPath,
rect
(at x=5,y=5, 100 wide and 100 high) stroking it in black and finally
filling it in red.
For comparison here is the equivalent code that doesn't use the
path function:
If you're interested in an RGraph.path function that works with any canvas
(ie your own) then take a look at
the SVG-like path function.
This is a function that is added to the 2D context
(when you include the code in your page) and makes creating and using canvas paths far
nicer. It looks like this:
The RGraph.path function is part of the
RGraph.common.core.js file and inside the RGraph classes it can be
referenced like this:
RGraph.path({
object: this,
path: 'b r % % % % f %',
args: [x, y, width, height, 'red']
});
Or this:
this.path(
'b r % % % % f %',
x, y, width, height,
'red'
);
Update (version 5.2)
The syntax for calling this function was extended so that you can call
it from either inside or outside of your chart object in these ways:
// The RGraph.path() function is added as a member function to each chart object
bar.path({
path: 'b r % % % % f red',
args: [x, y, width, height]
});
// A less verbose way of calling the function - similar to the sprintf function
bar.path('b r % % % % f red', x, y, width, height);
Working with events
When working with events, you may come across the situation where
you have a reference to the canvas, but
also need to access the chart object. For this reason, the
constructor of each RGraph chart object adds a reference to itself to the
canvas and you can access it like this:
<script>
document.getElementById("myCanvas").onclick = function (e)
{
var canvas = e.target;
// The RGraph object constructors add __object__ to the canvas.
var bar = canvas.__object__;
}
</script>
If you have multiple objects on your canvas (eg a combined Line chart
and Bar chart) the __object__ reference will be a reference to the last
object
that you added to the canvas. So in order to get other objects,
you'll
need to use the ObjectRegistry.
Working with chart coordinates
For many chart types, the coordinates of elements (eg bars, lines
etc) are to
be found in the variable obj.coords.
This is usually a multi-dimensional array consisting of the
coordinates of those shapes or points. As an example, the Bar chart
maintains the x y width and height of each bar (or sections
of bars in a stacked Bar chart). The coordinates array is
usually flat, even when you have multiple sets of data.
The obj.coords2 array is similar but
indexed slightly differently. Eg In a grouped Bar chart the
obj.coords2[0] array contains
all of the coordinates from the first group of bars - ie for a
group of three bars it will contain:
obj.coords2[0][0]
obj.coords2[0][1]
obj.coords2[0][2]
By using the RGraph.getMouseXY function and this array you can determine if a bar was clicked on, or if the mouse is near a
line point etc.
var coords = obj.coords;
Working with chart data
Another variable you may need is the data variable. For most chart types, this is where the data is stored. It is usually
untouched, so it is as you supplied to the chart objects constructor. A notable exception to this is filled Line charts.
Here the original data is stored in the variable obj.original_data. The data supplied is modified to produce the stacking
effect. If you need to modify a filled Line charts data you will need to change this variable instead.
Not all chart types use the data variable. For some, the name
is different so that it makes a little more sense. The
chart types and their associated data variables are listed below1.
The Line chart obj.original_data is an aggregation of all the datasets given to the Line chart, so the first
dataset is held in obj.original_data[0], the second in obj.original_data[1] etc.
For the Scatter chart, each data point is an array of X/Y coordinates, the color and the tooltip for that point.
Updating your charts dynamically
It is important that you're careful with types when making AJAX requests. Since the response is initially a string and your AJAX function/library may not do conversions for you, you may need to convert these strings to numbers. To do this you can use the javascript Number, parseInt or parseFloat functions. For example:
<script>
num = Number('23');
num = parseInt('43');
dec = parseFloat('43.5');
</script>
RGraph has AJAX helper functions that reduce type conversion hassles. You can read more about these functions in the AJAX HOWTO guide.
<script>
$.get('/getData.html', function (data)
{
// Use the console.log() function to show the returned data
console.log(data);
});
</script>
A common request is to be able to update charts dynamically.
This is quite straight-forward and consists of three steps:
Get your new data from the server (with an ajax request for example).
Set the data on your chart object. See the above table for the appropriate property to use.
Call the draw method again (you might need to use the RGraph.redraw function to fully
redraw the canvas if you have multiple charts)
If you don't need to get data from your server (ie it's all
client-side) then you can skip the first step. Also, it may be
sufficient to simply recreate the entire object from scratch.
This means that you won't have to update any
RGraph internal properties - just recreate the chart object
and configuration.
Note though that if you update the chart frequently (ie
multiple
times per second) then performance may be
slightly degraded.
Setting properties
To set RGraph properties you can use the json style
configuration (which is the default now) or you can use
each objects setter directly (there's also a corresponding
getter).
RGraph stores various references to objects on the canvas
(typically) to make getting hold of them easier. There's also a
Registry object in
which references and settings are stored. Typically the objects
are named with the format __xxx__ or with an obvious
prefix (such as the word rgraph), and you can inspect the
objects by using a console (eg the inspector that's part of Google
Chrome - press CTRL+SHIFT+J when viewing the webpage). Some examples are:
__object__ on the canvas - a reference to the chart object
RGraph.Registry.get('tooltip') - a reference to the currently visible tooltip (if any). This in turn has the following
available:
__text__ - Since setting innerHTML can cause changes in HTML, this is the original tooltip text.
__index__ - This is the numerical index corresponding to the tooltips array that you set.
__dataset__ - Used in some charts and corresponding to the dataset.
__canvas__ - A reference to the original canvas that triggered the tooltip.
RGraph.Registry.get('mousedown') - Used in annotating, and stipulates whether the mouse button is currently
pressed.
RGraph.Registry.get('contextmenu') - The currently shown context menu, if any. This in turn has the following
properties:
__canvas__ - The original canvas object.
These are just a sample of what's available, to find more you
should use an introspection tool or look at the source.
Scale information
For the Bar chart, Bipolar chart,
Horizontal Bar chart, Line chart,
Scatter chart and
Waterfall chart the scale that is used is stored in the
scale2 class variable. Eg:
<script>
bar = new RGraph.Bar({
id: 'cvs',
data: [56,43,52,54,51,38,46,42,52],
options: {
}
}).draw();
scale = bar.scale2;
</script>
Adding text to your charts
If you want to add arbitrary text to your chart(s) you can
either use
the RGraph.Drawing.Text drawing API object or use
the RGraph text
function directly. The drawing api object has advantages in
that it supports adding tooltips and/or click/mousemove events
to the text and is automatically redrawn for you.
So if you do use tooltips or other interactive features then you don't have
to worry about using the draw event.
The on() function for events
The events property is now the preferred way to set events on your chart object. You can read a bit more about this new property (new in version 6.22) and see an example of using it here.
The on function can be used to set events
(both custom and the click/mousemove events) on your canvas
without breaking
method chaining. For example:
bar = new RGraph.Bar({
id: 'cvs',
data: [4,8,6,4,3,5,4],
options: {
marginLeft: 35,
marginBottom: 35,
xaxisLabels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
}
}).on('draw', function (obj)
{
alert('Chart has been drawn!');
}).draw()
This is a list of some of the functions available to
you in the RGraph common libraries. Arguments in square
brackets are optional.
<script src="RGraph.common.core.js"></script>
<script>
// Returns 9
var arr = [3,2,5,4,9,7,8];
var max = RGraph.arrayMax(arr);
</script>
Type checking functions
Name: boolean RGraph.isString(mixed value)
Description:
Returns true or false depending on whether the supplied variable is a string or not.
Name: boolean RGraph.isNumber(mixed value)
Description:
Returns true or false depending on whether the supplied variable is a number or not.
Name: boolean RGraph.isNumeric(mixed value)
Description:
Returns true or false depending on whether the supplied variable is a numeric string or not (ie a string that looks like a number). Numeric types can include: 496 12.34 -78 6e78 -6.59e-3 0xab Infinity -Infinity 0 -0 Newer types (eg Binary, BigInt are not accommodated for).
Name: boolean RGraph.isTextual(mixed value)
Description:
Returns true or false depending on whether the supplied variable is either a string, a number (both true) or not (false).
Name: boolean RGraph.isBoolean(mixed value)
Description:
Returns true or false depending on whether the given value is a boolean (true or false) or not.
Name: boolean RGraph.isArray(mixed value)
Description:
Returns true or false depending on whether the given value is an array or not.
Name: boolean RGraph.isObject(mixed value)
Description:
Returns true or false depending on whether the given value is an object or not. Note that if you give null to this function you'll be returned false - even though technically null is an object If you want to test for null values then you need to use the RGraph.isNull or the RGraph.isNullish functions.
Name: boolean RGraph.isNull(mixed value)
Description:
Returns true or false depending on whether the given value is null or not.
Name: boolean RGraph.isNullish(mixed value)
Description:
Returns true or false depending on whether the given value is null or if the value is undefined.
Name: boolean RGraph.isFunction(mixed value)
Description:
Returns true or false depending on whether the given value is a function or not.
Name: boolean RGraph.isUndefined(mixed value)
Description:
Returns true or false depending on whether the given value is undefined or not.
GET functions
Name: string RGraph.GET.string(string name)
Description:
Fetches a query-string parameter (the type of the returned value is String).
Name: number RGraph.GET.number(string name)
Description:
Fetches a numeric query-string parameter (the returned values type is Number).
Name: object RGraph.GET.json(string name)
Description:
Fetches a json query-string parameter (the returned values type is Object). With this function, you can pass multiple bits of data on the query-string because objects can hold multiple values and as a result, this is much more versatile than the other functions.
Fetches an array from the query-string. Your array may or may not have the enclosing square brackets and you can pass an optional second string argument that will be used as the separator.
Clipping functions
There is now (from version 6.17) a new clip property that has been added to both the canvas and SVG chart types which eliminates the need to use these clipping functions and is a lot easier for you to add to your charts. You can read about the clip configuration property here.
This function can be used to clip the canvas (which, using the
standard canvas api functions, can
be a somewhat verbose procedure) in order to facilitate
a variety of things including multi-color Line charts
(there are demos of such charts in
the download archive
called line-clipping1.html line-clipping2.html
line-clipping3.html and line-clipping4.html). The
second argument can be a string or an array and there are
examples of each way that you can use the function shown
on the clipping documentation page.
Because, using this technique, the clipping starts before
RGraph applies an antialiasing fix and then the
canvas is restored to that state, the second
chart may not be correctly antialiased. If this is the
case then you may need to add this line of code between the
drawing of each
your charts to reset the antialiasing flag that RGraph
uses:
// Sometimes this may be necessary to reset the antialiasing fix that RGraph applies to the canvas
obj.canvas.__rgraph_aa_translated__ = false;
Name: null RGraph.clipTo.end()
Description:
Complements the above function and ends clipping. See above for examples of use.
Array functions
Name: number RGraph.arrayMin(array array)
Description:
Returns the minimum value in the array.
Name: number RGraph.arrayMax(array array)
Description:
Returns the maximum value in the array.
Name: number RGraph.arraySum(mixed array)
Description:
Returns the sum of all of the values in the array. You can also pass a single number, in which case it is simply returned as-is.
Creates a copy of the given object or array. The implementation of this function has changed in the version 6.18 release. Instead of using the JSON.parse(JSON.stringify(obj)) method it now loops through each element copying it or recursing into it (in the case of an array or an object) and "manually" copying it to the new array (or object).
var original_array = [4,6,8,['blah',44,7,null],3,2,5];
var myCopy1 = RGraph.arrayClone(original_array, true);
At some point in the future the default value for the objects parameter will be changed to true but for now, if you want to clone objects as well as arrays then you must set this parameter to true.
Name: array RGraph.arrayReverse(array array)
Description:
Returns a reversal of the given array.
Name: boolean RGraph.isArray(array array)
Description:
Returns true or false as to whether the given object is an array or not.
Name: array RGraph.arrayPad(array array, number length[, mixed value = null])
Description:
Pads the given array to the specified length (if the length of the array is less than this, if not the array is returned as is). The third, optional, argument is the value that is used as the pad value. If not specified, null is used.
Name: array RGraph.arrayShift(array array)
Description:
Shifts an element off of the start of the given array and returns the new array.
Name: array RGraph.arrayColumn(array array, number column)
Description:
In a 2D array this function, when passed the array and a column index, will return each of those indexes from the array - essentially a column from that array. So in the example array the highlighted elements are returned as a new array:
<script>
var myArray = [
[546,'Richard',12],
[351,'John',56],
[846,'Lucy',43],
[777,'Barbara',12]
];
var newArray = RGraph.arrayColumn(myArray, 1);
// Returns:// ['Richard','John','Lucy','Barbara']
This function takes any number of arrays as arguments and concatenates them all into one big array. Similar to the standard javascript concat string function.
This function can be used to convert sequential indexes (such as tooltips or the coords array) into grouped indexes. For example, you may have an index of 5 (which starts at 0 remember), but need to convert it into one that is usable with the data: [[4,6,5],[4,3,2],[1,5,2]] (eg a stacked/grouped bar chart). This function will do that for you. It returns a two-element array containing the group index and the index into that group. So your index of five becomes: [1, 2]
Name: number RGraph.groupedIndexToSequential(array data, number dataset, number index)
Description:
This function does the opposite of the above and converts a dataset and index (ie a grouped index) into a sequential index (a grouped or stacked Bar chart uses grouped data). For example:
var data = [
[4,8,5,6,2],
[4,4,1,2,3],
[9,8,6,5,3]
];
seq = RGraph.groupedIndexToSequential(data,2,2);
// seq is now 12
Name: array RGraph.arrayInvert(array)
Description:
This function can be used to invert values in an array from truthy to falsey and vice-versa. So an array containing two truthy values and six falsey values becomes an array of two falsey values and six truthy values.
Name: array RGraph.arrayRandom(number num, number min, number max)
Description:
This function provides an easy way to generate an array filled with num random values between min and max.
When you pass this function an array or an object the null values in it will be removed. By default, objects aren't touched however if you give an object as the second argument which has the key objects (for example RGraph.arrayRemoveNull(myArray, {objects: true})) then null values will be removed from objects too. If you give a value parameter to the options array null values will not be removed, but substituted with that value instead.
This function operates similarly to the Math.abs function except that it also handles arrays and objects (recursively). It applies the Math.abs function to each element.
Name: string RGraph.random(number min, number max)
Description:
Returns a random number between the minimum and maximum that you give. To get an array filled with random values you can use the RGraph.arrayRandom function detailed above.
Name: string RGraph.numberFormat(object options)
Description:
This formats the given number (which can be either a number or a float. The prepend and append options are string values that are added to the number that you give (eg 5%).
Note: As of the January 2019 release this functions argument list has been changed to accept a single object instead of multiple separate arguments. So you can call this function like this:
This function returns the logarithm value for the given number using the given base.
Miscellaneous functions
Name: object RGraph.addCss(string selector)
Description:
This function adds a CSS rule to the document. Used predominantly by the datagrid, you can give it an entire CSS selector and its styles and this function will add it to the document for you in the head section. If it has been called previously it will reuse the style HTML tag from the previous call. For example:
This function parses a configuration string into a javascript object. The separator argument is the character on which to split the string. So if you have a string like this:
name=value,name2=value2,name3="A quoted value with spaces"
This function will parse it and return you an object:
{
name: value,
name2: value2
name3: A quoted value with spaces
}
This is the function to use if you want to clear the canvas or window official dom2 event listeners (ie that facilitate things like tooltips). The id argument that you pass it should be either the id of the canvas (the same as what you pass to document.getElementById), or just window if you want to clear the window event listeners. Keep in mind though that if you clear the window event listeners it will affect all canvas tags on the page.
Name: string RGraph.createUID()
Description:
This function is used to create a unique id for each object (which is done in their constructor). This uid can then be used to identify a single object. There's an associated ObjectRegistry method: RGraph.ObjectRegistry.getObjectByUID which can then be used to retrieve an object with that uid.
Name: object RGraph.Effects.wrap(object canvas)
Description:
This function is used by some animation effects to stop the page layout from changing when the canvas is removed from the document. It removes the canvas from the document, replaces it with a div and then adds the canvas as a child node of the div. The canvas is placed in the center of the div.
Name: null RGraph.pr(mixed value)
Description:
Emulates the php function print_r by recursively printing the structure of whatever you pass to it. It handles numbers, strings, arrays, booleans, functions and objects.
Name: null $p(mixed value)
Description:
An alias of the above albeit shorter to type.
Name: null $cl(mixed value)
Description:
A shortcut for the debug function console.log.
Name: null $c(mixed value)
Description:
Another (even shorter) shortcut for the debug function console.log.
Clears the canvas by drawing a clear (or the optional color you give) rectangle over it. If you don't specify a color and your chart (or if you have multiple charts on the canvas - the last chart that you created) has the clearto option specified (eg obj.set('clearto', 'white') ) then this function will use that color when clearing the canvas - essentially a default clear color.
Name: null RGraph.clearAnnotations(object canvas)
Description:
This function clears the annotation data associated with the given canvas (but does not redraw the chart). If you want to clear the visible annotations too, you will need to redraw the canvas. You could do this using the following code:
function clearAndRedraw (obj)
{
RGraph.clearAnnotations(obj.canvas);
RGraph.clear(obj.canvas);
obj.draw();
}
Name: null RGraph.replayAnnotations(object obj)
Description:
This function redraws any annotations which have previously been drawn on the canvas. You would use this function when annotations are turned off and you want previous annotations to be displayed. You pass the chart object as the argument.
Name: array RGraph.getMouseXY(object event)
Description:
When passed an event object, it returns the x and y coordinates (in relation to the canvas) of the mouse pointer. (0,0) is in the top left corner, with the x value increasing going right and the y value increasing going down.
Name: array RGraph.getScale(object options)
Description:
Given the maximum value, this function will return an appropriate scale. The argument is an object which can contain two properties - object (the chart object) and options (an object containing configuration properties). The options object can contain these properties:
scale.max
The maximum value
scale.min
The minimum value
scale.labels.count
Number of labels to generate.
scale.units.pre
These units are placed before the number.
scale.units.post
These units are placed after the number.
scale.strict
Giving a max value of (for example) 96 will generate a scale that goes to 100 - though if you specify the strict option you will get a scale that goes to 96.
scale.decimals
The number of decimals to show.
scale.point
The character that's used to indicate a decimal point (the default is ".").
scale.thousand
The character that's used to indicate a thousand separator (the default is ",").
scale.round
Whether to round the scale up. eg A scale might be generated with a maximum value of 600, whereas if you specify this option the scale would be rounded to 1000.
Name: mixed RGraph.Registry.get(string name)
Description:
In conjunction with the next function, this is an implementation of the Registry pattern which can be used for storing settings.
In conjunction with the previous function, this is an implementation of the Registry pattern which can be used for storing settings.
Name: null RGraph.register(mixed value)
Description:
This function is used in conjunction with the next to register a canvas for redrawing. canvas tags are redrawn (for example) when tooltips or crosshairs are being used. See the section below for details on the RGraph ObjectRegistry which is used to facilitate multiple charts on one canvas. The argument should be an RGraph object or from January 2022 it can also be a regular function. If it's a function then it will be run when the RGraph.redraw function is run (not the RGraph.redrawCanvas function).
Name: mixed RGraph.redraw(mixed color = transparent)
Description:
This function is used in conjunction with the previous to redraw a canvas. canvas tags are redrawn (for example) when tooltips or crosshairs are being used. Note: All canvas tags that are registered are redrawn. The optional argument is the color to use when clearing the canvas tags.
Similar to the redraw function but this only redraws the specified canvas tag (instead of all (RGraph) canvas tags on the page). The clear argument determines whether to clear the canvas before redrawing and the color argument allows you to specify a color when the canvas is being cleared.
Name: null RGraph.setShadow(object obj, mixed color, number offetX, number offsetY, number blur)
Description:
This function is a shortcut function used to set the four shadow properties. The arguments are: your chart object, the shadow color, the x offset, the y offset and the shadow blur. An alternative way to call this function is like this:
This would then look for the four shadow properties on the object all of which have the shadow prefix (ie shadowColor shadowOffsetx shadowOffsety and shadowBlur). The third way that you can call this function is by just giving it a solitary RGraph object. In this case the shadow will be turned off - just like the RGraph.noShadow function below.
Name: null RGraph.noShadow(object obj)
Description:
This is a shortcut function used to "turn off" the shadow. The argument is your chart object.
Name: number RGraph.async(function function[, number delay = 1])
Description:
This is a simple function but has significant implications on the performance of your page. You can pass this either a function, or a string containing the code to run and it will run the code asynchronously (ie in parallel to the page loading). In doing so it can mean that your page is displayed faster, as the chart is created separately from the page loading. As such, the placement of your canvas tag becomes more important. What you can do is define the canvas tag and then the code to produce the chart immediately after it.There's an example of it on the async documentation page. The optional delay argument is measured in milliseconds (1 second = 1000 milliseconds) and defaults to 1. What you can do is specify something like 1000 to make the effect more pronounced to ensure it's working as expected.
Name: null RGraph.roundedRect(object context, number x, number y, number width, number height[, number radius = 3[, boolean roundtl = true[, boolean roundtr = true[, boolean roundbl = true[, boolean roundbr = true]]]]])
Description:
This draws a rectangle with rounded corners. It's similar to the built-in rectangle functions and you can control individual corners. The radius controls the severity of the corner curvature and defaults to 3. By default all of the corners are rounded. Note that the rectangle is not filled or stroked. So to create a rounded rectangle you'll need to do something like this (the arguments to the function can be given in the traditional style like in the function definition above or as properties of a single object like in the example code here):
This function resets the canvas. At first, this function may appear similar to the RGraph.clear function, however, it will reset any translation that has been performed so it can stop them from accumulating. It also clears the ObjectRegistry for the specified canvas - so if you use one canvas to show multiple charts (not all at once - one at a time) you may need to use this method prior to showing each chart.
This is a shortcut function for creating a linear gradient. You specify the x and y coordinates and the colors and it returns the gradient. You can specify more than two colors if you want to. An example of how to use this function is:
This is a shortcut function for creating a radial gradient. You specify the x and y coordinates, the radius and the colors and it returns the gradient. You can specify more than two colors if you want to.
This is an update of the original RGraph.path function which supports more operations and has even more concise syntax. You don't need to choose between the two path functions - just use RGraph.path Inside the RGraph source code, you'll see this being referenced as this.path You can read all about this function and see the available path options in this blog article.
Name: number RGraph.parseDate(string date[, string units])
Description:
The RGraph.parseDate function is similar to the Date.parse function in that it takes a date string and returns a number which is the number of milliseconds since January 1st 1970 (though the returned value can also be seconds if you pass an s to the function as the second argument). It goes a little further than the Date.parse function by allowing extra formats of date/time - for example:
2013-11-22 12:12:12
2013/11/22 12:12:12
2013-11-22
12:09:44 (today's date is used)
June 21st 1984
Other formats are supported - so just try yours and see!
All the formats that Date.parse natively supports are
also supported.
This fires a custom event. The object is your chart object, and the name is a string specifying the name of the event.
Name: number RGraph.addCustomEventListener(object obj, string event, function callback)
Description:
This attaches a function to the specified event. The object argument is your chart object, the event argument should be the name of the event, eg tooltip, and the function argument is your function which handles the event The return value is an id which can be used with the RGraph.removeCustomEventListener function.
Name: null RGraph.removeCustomEventListener(object obj, number id)
Description:
This removes the custom event listener that corresponds to the given id The arguments are the chart object and the id of the event listener to remove (as returned by the RGraph.addCustomEventListener function).
To easily remove all custom event listeners you can use this function. It can also optionally take one argument - an RGraph object uid - to limit the clearing to a particular object. For clearing the standard event listeners that RGraph installs - see the miscellaneous section
Trigonometry functions
Name: number RGraph.toRadians(number degrees)
Description:
Converts and returns the given number of degrees to radians. Roughly, 1 radian = 57.3 degrees.
Name: number RGraph.toDegrees(number radians)
Description:
This is a function that does the reverse of the above function and converts radians to degrees.
Name: number RGraph.getAngleByXY(number cx, number cy, number x, number y)
Description:
Given two pairs of coordinates, this function will return the angle that a line connecting them creates.
Name: number RGraph.getHypLength(number x1, number y1, number x2, number y2)
Description:
Using "Pythagoras theorem" this function will return the length of the line connecting the two points.
Name: number RGraph.getRadiusEndPoint(number x, number y, number angle, number radius)
Description:
Using trigonometry functions (sin / cos) this function returns you the coordinates of the endpoint of a radial line. You give it the center x and y coordinates, the angle and the radius.
Name: null RGraph.rotateCanvas(object canvas, number x, number y, number angle)
Description:
This function can be used before you draw your chart to rotate the canvas. The canvas is rotated about the x / y coordinates that you give, by the angle (which is measured in radians). Angles can be negative.
Other functions
These are less generic functions and are used to build the charts. You may still wish to use them, however.
Name: object RGraph.text(object options)
Description:
This function is a rewrite of the original text function. It's faster than its predecessor and its return value is an object that contains the coordinates of the text (unless the text is angled). These coordinates are also stored on the given object in the obj.coordsText array. By using these coordinates in conjunction with the drawing api Rect object you can create clickable text. An easier alternative to that though may be to simply use the Drawing API Text object. The various properties that you can use with this function are:
object
An RGraph object that's used to get the context from.
color
The color used to draw the text.
font
The font used to draw the text.
size
The size used to draw the text (in points).
italic
Whether the text is italicised or not.
bold
Whether the text is bold or not.
x
The x coordinate of the text.
y
The y coordinate of the text.
text
The text to display.
bounding
Whether to draw a bounding box around the text.
boundingStroke
The stroke color of the bounding box.
boundingFill
The fill color of the bounding box.
boundingShadow
Whether the bounding box has a shadow.
boundingShadowColor
The color of the shadow.
boundingShadowBlur
The severity of the shadow blur.
boundingShadowOffsetx
The x offset of the shadow.
boundingShadowOffsety
The y offset of the shadow.
boundingLinewidth
The linewidth used to draw the bounding box.
marker
Whether to show a positioning marker.
halign
The horizontal alignment of the text. This can be left, center or right.
valign
The vertical alignment of the text. This can be bottom, center, top or now (from the January 2022 release) it can also be alphabetic
tag
This can be used to supply a helpful identifier that can later be used to search for the text in the obj.coordsText array
accessible
Whether to use accessible dom text or not. The default is to not use accessible text.
If you use accessible text then you can use this function to retrieve the dom nodes (that are span tags) of the text. The options argument should be an object that contains the details of what you want to search for. The arguments are ORed, so if you specify two criteria and two different nodes match - both nodes will be returned. The object can contain the following:
id
The id of the canvas tag. If you prefer you can give the object argument instead.
object
An RGraph object that's used to get the context from.
tag
This can be a string or a regular expression that is matched against the tag of the text.
text
This can be a string or a regular expression that is matched against the text.
callback
This can be a function that is called when the search has completed and any matching nodes have been found. The function is given an object as its sole argument. This object has two properties - nodes which is an array of any matching nodes that have been found and object which is the chart object.
// Using a string of text as the tag
var nodes = RGraph.text.find({
id: 'cvs',
tag: 'labels'
});
// Using a regex as the tag
var nodes = RGraph.text.find({
object: myBar,
tag: /^lab/
});
// Using a string as the text option
var nodes = RGraph.text.find({
id: 'cvs',
text: '10km'
});
// Using a regex as the text option
var nodes = RGraph.text.find({
id: 'cvs',
text: /^10/
});
// Using the callback option
var nodes = RGraph.text.find({
id: 'cvs',
text: /^10/
callback: function (args)
{
var obj = args.object,
nodes = args.nodes;
// Do something here
}
});
Remember that this function only works if you use accessible text.
Name: null RGraph.drawTitle(object obj, string text, number margin[, number centerx[, number size]])
Description:
This function draws the title. The centerx argument is the center point to use. If not given the center of the canvas is used.
Name: null RGraph.tooltip(object obj, string text, number x, number y, number index, object event)
Description:
This function shows a tooltip. The index value that you give corresponds to the tooltip property array. The event argument is the event object.
Name: null RGraph.hideTooltip([object canvas])
Description:
This function hides the tooltip. The optional argument can be a canvas object (the same as what you're returned from the document.getElementById) function and if given, the tooltip is only cleared if it originates from that canvas.
This function draws the key. The first argument is the chart object, the second is an array of the key items and the last is an array of the colors to use.
Name: null RGraph.drawBars(object obj)
Description:
This draws the horizontal background bars. The argument is the RGraph chart object.
Name: null RGraph.drawIngraphLabels(object obj)
Description:
This draws the ingraph labels. The argument is the RGraph chart object.
Name: null RGraph.drawCrosshairs(object obj)
Description:
This function draws the crosshairs. The argument is the RGraph chart object.
Name: null RGraph.hideContext()
Description:
This function clears the contextmenu. RGraph uses it to hide the contextmenu, but only after your callback is run. You may wish to hide the contextmenu before your own function, in which case you can call this function.
Optionally, you can pass in the canvas as an argument that will be used, meaning now you do not have to use a contextmenu (there's an example here). It was originally designed to be used with a contextmenu though, hence it's part of the RGraph.common.context.js file.
Name: null RGraph.Background.draw(object obj)
Description:
This function is used by the Bar chart Gantt chart HBar chart Line chart Scatter chart and Waterfall chart to draw the background (but not the axes). It is passed the chart object which it uses to get the properties it uses:
margin
variant
textSize
textFont
title
xaxisTitle
xaxisTitlePos
yaxisTitle
yaxisTitlePos
backgroundBarsColor1
backgroundBarsColor2
backgroundGrid
backgroundGridWidth
backgroundGridAlign
backgroundGridAlines
backgroundGridAlines
backgroundGridHlinesCount
backgroundGridVlinesCount
backgroundGridColor
backgroundGridBorder
Note that this function also calls RGraph.drawTitle in order to draw the title.
Name: null RGraph.drawBackgroundImage(object obj)
Description:
This function draws the backgroundImage for the chart (the Line chart Bar chart Scatter chart and Waterfall chart). When you use background images there is a very small delay between calling the canvas 2D drawImage api function and the image then loading. Because of this when you call the drawImage function the image isn't loaded yet. Therefore when the image is loaded, the RGraph drawBackgoundImage function does a redraw so that the image is drawn onto the canvas.
Name: null RGraph.AJAX(string url, function callback)
Description:
This function can be used to make ajax requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as an argument (it's provided to you as a string). You would use it like this:
<script>
RGraph.AJAX('/getdata.html', function (str)
{
// Handle the response and create the chart
});
</script>
Name: null RGraph.AJAX.getString(string url, function callback)
Description:
This function can be used to make ajax requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as an argument. This function is much the same as the above function though because of the name, it may aid you by being more of a visual prompt. You would use it like this:
<script>
RGraph.AJAX.getString('/getdata.html', function (str)
{
// Handle the response and create the chart
});
</script>
Name: null RGraph.AJAX.getNumber(string url, function callback)
Description:
This function can be used to make ajax requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as an argument but it's automatically converted to a number for you (using the javascript parseFloat function). You would use it like this:
<script>
RGraph.AJAX.getNumber('/getdata.html', function (number)
{
// Handle the response and create the chart
});
</script>
Name: null RGraph.AJAX.getJSON(string url, function callback)
Description:
This function can be used to make ajax requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as a javascript object (your json string is parsed using eval('(' + response + ')'). You would use it like this:
<script>
RGraph.AJAX.getJSON('/getdata.html?json', function (json)
{
// Handle the response and create the chart
});
</script>
Name: null RGraph.AJAX.getCSV(string url, function callback[, string separator = ","])
Description:
This function can be used to make ajax requests to your server (eg to fetch new data without refreshing the page). The response text is given to your callback function as a javascript array which is created from the first line of your csv data). You would use it like this:
<script>
RGraph.AJAX.getCSV('/getdata.html', function (csv)
{
// Handle the response and create the chart
}, ',');
</script>
Name: null RGraph.dashedLine(object context, number x1, number y1, number x2, number y2[, number size])
Description:
This function can be used to add dashed or dotted lines to your canvas. The arguments are the context, the start coordinates and the end coordinates. You can optionally specify a fifth argument which is used as the size of the dashes (the default is 5px).
Name: mixed RGraph.runOnce(string id, function func)
Description:
As the name suggests this function runs the given function once and once only (even if it's in a loop). It works by keeping a record of the id that you give and if it's been given that id before then it simply returns without running the function. There's no delay involved in running the function - if that id hasn't been seen before it runs immediately. It returns whatever the function returns.
Name: mixed RGraph.runOnce(string id, function func)
Description:
As the name suggests this function runs the given function once and once only (even if it's in a loop). It works by keeping a record of the id that you give and if it's been given that id before then it simply returns without running the function. There's no delay involved in running the function - if that id hasn't been seen before it runs immediately. It returns whatever the function returns.
Name: number RGraph.PHP.time([string modifier])
Description:
This is a javascript implementation of the php time function which returns the number of seconds since the unix epoch (which is 00:00:00 UTC on 1 January 1970) The optional argument can be a string that you can use to modify the timestamp that's returned. For example:
RGraph.PHP.time();
RGraph.PHP.time('now + 1 year'); // OR now + 1y
RGraph.PHP.time('now + 2 weeks'); // OR now + 2w
RGraph.PHP.time('now + 14 days'); // OR now + 14d
RGraph.PHP.time('now - 24 hours'); // OR now - 24h
RGraph.PHP.time('now - 60 minutes');// OR now - 60m
RGraph.PHP.time('now - 10 seconds');// OR now - 10s
Name: string RGraph.PHP.date(mixed format[, number timestamp])
Description:
This is a javascript implementation of the php date function which allows you to easily create dates that are formatted to your own specification. Optionally, You can give this function a unix timestamp - the same as what is returned from the function above - in order to get different dates than the current time/day. This is a simple number so it's easy to manipulate and thus get the date that you want, formatted as you want. The timestamp argument can also be a string and if that's the case then this string is passed over to the RGraph.PHP.time function (above) in order to get a timestamp, modified as requested. Some examples of using it are:
// 12:02 17th January 2025
RGraph.PHP.date('H:i jS F Y');
// 2025-05-17 12:02:03
RGraph.PHP.date('Y-m-d H:i:s');
// 2016-10-31 20:02:03
RGraph.PHP.date('Y-m-d H:i:s', 1477944123);
// 2026-05-19 12:08:05 (See the RGraph.PHP.time() function// above for the possibilities that you// have to modify the timestamp.)
RGraph.PHP.date('Y-m-d H:i:s', 'now + 1y + 2d');
The date formatting options that you have available to you are the
same as the original php function which are documented
on the PHP documentation for the date function. Note: The following php options do not work in the javascript version of the function: X x v e p
The RGraph ObjectRegistry
The RGraph ObjectRegistry allows you to have
multiple charts on a single canvas - both having
dynamic features.
You can combine any of the chart types in RGraph, such as
Meter charts, Gauge charts,
Progress bars etc. Because it's a common
combination, there's a special class for the combined Bar chart and
Line chart which you use like this:
<script>
bar = new RGraph.Bar({
id: 'cvs',
data: [4,8,5,7,8,9],
options: {
xaxisLabels: ['Alex','Doug','Charles','Nick','Michelle','Ali'],
colors: ['red'],
tooltips: ['Alex','Doug','Charles','Nick','Michelle','Ali'],
textSize: 14,
marginInner: 20,
combinedEffect: 'wave',
yaxis: false,
backgroundGridVlines: false,
backgroundGridBorder: false
}
});
line = new RGraph.Line({
id: 'cvs',
data: [3,9,4,9,6,5],
options: {
textSize: 14,
colors: ['black'],
linewidth: 2,
tooltips: ['1984','1985','1986','1987','1988','1989'],
shadow: false,
spline: true,
combinedEffect: 'trace'
combinedEffectOptions: '{frames: 60}'
}
});
// Create the combination object - this draws the chart
combo = new RGraph.CombinedChart(bar, line).draw();
</script>
You can have as many chart types as you want with the CombinedChart class, but the Bar chart should be the first one that you
add to it. Because it's a common combination, the CombinedChart class changes the Line chart margins to match the Bar charts.
When you create an object it's added to the ObjectRegistry automatically so that it can be redrawn as needed. objects are
indexed by canvas id and also by uid. This means that you can quickly get hold of all of the pertinent objects for a
given canvas, or one particular object if you need it. The following methods are available:
Note:
You can also use these aliases:
RGraph.OR
An alias to RGraph.ObjectRegistry (you can use this alias with all the ObjectRegistry functions).
RGraph.OR.firstbyxy
An alias to RGraph.ObjectRegistry.getFirstObjectByXY
RGraph.OR.get
An alias to RGraph.ObjectRegistry.getObjectByUID
RGraph.OR.type
An alias to RGraph.ObjectRegistry.getObjectsByType()
RGraph.OR.first
An alias to RGraph.ObjectRegistry.getFirstObjectByType()
ObjectRegistry functions
Name: null RGraph.ObjectRegistry.add(object obj)
Description:
This method adds an object to the ObjectRegistry. It's used predominantly by the RGraph.register function.
This method removes an object from the ObjectRegistry. You may need to use this if you draw multiple charts on the same canvas otherwise all of the objects that you have created will be drawn when you redraw the canvas.
This method clears the ObjectRegistry back to a state where nothing is registered. You can optionally give it either a canvas tag id (a string) or the actual canvas tag itself (as returned by document.getElementById) and the clearing of the ObjectRegistry will be limited to that canvas.
The iterate function provides an easy way to go through all or some of the objects in the ObjectRegistry. The first argument should be a function that is called for every matching object in the ObjectRegistry. By default, this function iterates through each object in the ObjectRegistry, but the second argument can be a comma-separated list of one or more desired object types and the sole argument passed to the function is the object. Some examples of its usage:
// Iterate through all of the objects in the ObjectRegistry
RGraph.ObjectRegistry.iterate(function (obj)
{
alert('The objects UID is: ' + obj.uid);
});
// Iterate through all of the bar chart objects in the ObjectRegistry
RGraph.ObjectRegistry.iterate(function (obj)
{
alert('The objects UID is: ' + obj.uid);
}, 'bar');
// Iterate through all of the bar,line and pie chart objects in the ObjectRegistry
RGraph.ObjectRegistry.iterate(function (obj)
{
alert('The objects UID is: ' + obj.uid);
}, 'bar,line,pie');
This method takes an event object and returns the pertinent object. It only returns a single object - unlike the function below - so you may find it easier to use if, for example, you're creating a bank of Meters or Gauges.
This method takes an event object and returns the objects that the mouse is positioned over. It returns an array of chart objects because there may be multiple applicable objects (eg a Bar chart and Line chart combined.
This method takes a uid (which can be retrieved with obj.uid) and returns the pertinent object. Note that uids are unique to a single page request only. So if you refresh the page they'll change. They can be used, however, to distinguish between objects in a single request.
This method returns an array of objects that are of the given type. As of January 2013, its arguments list has changed so now it just takes the desired type of object (eg pie line bar etc).
As of January 2013, the argument list for this function has changed - it now only accepts one argument - the type (eg pie bar line) and returns the first object that is in the ObjectRegistry that has that type.
This method removes an object from the ObjectRegistry and pushes it onto the end - essentially moving the object to the top/front of the stacking order.
Note:
Since the ObjectRegistry was introduced objects have to be
registered regardless of whether they use dynamic features
or not. As a result of this, you may be experiencing objects
being redrawn when you don't want them to be. To
solve this you need to remove them from the ObjectRegistry.
How to remove an object from the ObjectRegistry is documented here.