Show the navigation menu
RGraph: HTML5 charts library

API Documentation


 

Overview

Working with RGraph objects is purposefully easy, to make them straight forward 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:

<script src="RGraph.common.core.js"></script>
<script src="RGraph.bar.js"></script>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

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 zoom functions reside in RGraph.common.zoom.js, so if you don't need zoom, 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 which are included in the archive. If you want to create your own chart type you can use one of the drawing objects as a starting point.

 

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>
    $(document).ready(function ()
    {
        // 1/2 First draw the chart
        var bar = new RGraph.Bar({
            id: 'cvs',
            data: [1,5,8,4,6,3,1,5,7,8,4,6],
            options: {
                labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            }
        }).draw()
    
        // 2/2 Now get hold of the references
        var context = myBar.context; // Get hold of a reference to the context
        var canvas  = myBar.canvas;  // Get hold of a reference to the canvas
    })
</script>

 

The short variables (for example RG, ca, co, prop, pa, ma, jq)

Because local variables are a very fast type of variable - RGraph uses these variables thoughout all of the libraries. You'll see these as RG, ca, co, prop, pa, ma and jq - they're just short names for variables that are used throughout the RGraph code

If you look through the RGraph source you might see the pa() function in use from October 2013 onwards (short for path). This function makes the canvas path syntax, which is quite verbose, much less so. As an example:

pa(context, ['b','r',5,5,100,100,'s','black','f','red'])

This is a shorter way of doing a beginPath(), rect() (at x=5,y=5 100 wide 100 high) stroking it in black and finally filling it in red.

Short name Description
RGThe RGraph global variable
caThe canvas
coThe context
propThe objects properties
paThe RGraph.Path() function
jqjQuery
winThe window object
docThe document object
maThe Math object

 

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 object adds a reference to the object to the canvas and you can access it like this:

<script>
    document.getElementById("myCanvas").onclick = function (e)
    {
        var src = (RGraph.ISIE8 ? event.srcElement) : e.target;
    
        // The RGraph object constructors add __object__ to the canvas.
        var myBar = src.__object__;
    }
</script>

 

Working with chart coordinates

For most chart types, the coordinates of elements (eg bars, lines etc) are to be found in the object variable obj.coords. This is usually a multi-dimensional array consisting of the coordinates of those shapes, or of 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 coords array is usually a flat array, even when you have multiple sets of data.

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 myCoords = myBar.coords;

Note: Previously the coords array values sometimes included the margin values, and sometimes didn't. As of 17th April 2010 the values have all been unified to not include the margin values, so the values are as reported.

Note: The Line chart also has an object variable myObj.coords2, where the coordinates are indexed differently - by line index.

 

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 class variable 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 associate data variables are listed below1.

Chart type Data variable(s)
Bar obj.data
Bi-polar obj.left, obj.right
CornerGauge obj.min, obj.max, obj.value
Donut This is now a variant of the Pie chart
Fuel obj.min, obj.max, obj.value
Funnel obj.data
Gantt See the docs
Gauge obj.min, obj.max, obj.value
Horizontal Bar obj.data
Horizontal Progress bar obj.max, obj.value
Line obj.original_data3
Meter obj.min, obj.max, obj.value
Odometer obj.start, obj.end, obj.value
Pie obj.angles, obj.data
Radar obj.original_data, obj.max
Radial Scatter chart obj.data
Rose obj.max, obj.data
Scatter obj.max, obj.data2
Thermometer obj.min, obj.max, obj.value
Vertical Progress bar obj.max, obj.value
Waterfall chart obj.max, obj.data
  1. In the table, obj refers to your chart object.
  2. For the Scatter chart, each data point is an array of X/Y coordinates, the color and the tooltip for that point.
  3. 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.

 

Updating your charts dynamically

Note: 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 Number() or parseInt() functions. For example:

<script>
    num = Number('23');
    num = parseInt('43');
</script>

The May 2013 release added AJAX helper funcions that minimise type conversion hassles. You can read more about these functions in the AJAX HOWTO guide.

A common request is to be able to update charts dynamically. This is quite simple and consists of three steps:

  1. Get the new data from the server (with an AJAX request for example).
  2. Set the data in your chart object. See the above table for the appropriate property to use.
  3. Call the .draw() method again (you might need to use the RGraph.redraw() function to fully redraw the canvas if, for example, you have multiple charts)

If you don't need to get data from your server (ie it's all client-side) then you can omit the first step. Also, it may be sufficient to simply recreate the entire object from scratch. This means that you won't have to alter any RGraph internal properties - just recreate the chart object and configuration.

 

Setting properties

To set RGraph properties you can (ideally) either use the tree base JSON style configuration (new in July 2014) or you can use each objects setter directly (there's also a corresponding getter). The set() functions accomodate some backwards compatibility changes, so by not using them (or JSON style configuration) you run the risk of your charts not working entirely as expected.

myObj.set('gutter.left', 25);
myObj.get('gutter.left');

You can read more about the JSON style here.

 

References available on RGraph objects

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 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 - CTRL+SHIFT+J). Some examples are:

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, Bipolar, HBar, Line and Scatter charts the scale that is used is stored in the scale2 class variable. Eg:

<script>
    var myBar = new RGraph.Bar({
        id: 'cvs',
        data: [56,43,52,54,51,38,46,42,52]
    }).draw();
    
    var myScale = myBar.scale2;
</script>

 

Adding text to your charts

If you want to add arbitrary text to your chart(s) you can either use the Text drawing API object or use the RGraph functions directly. The drawing API object has advantages in that it supports you 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 ondraw event.

 

The .on() function for events

The on() function can be used to set events (both custom and the click/mousemove events) on your canvas withou breaking method chaining. For example:

var bar = new RGraph.Bar({
    id: 'cvs',
    data: [4,8,6,4,3,5,4],
    options: {
        gutter: {
            left: 35,
            bottom: 35
        },
        labels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
    }
}).on('draw', function  (obj)
{
    alert('Chart has been drawn!');
}).draw()

 

RGraph functions

This is a list of some of the functions available to you in the RGraph common libraries. It's not every single one that's available, but is a list of the common ones that you're likely to want to use. Arguments in square brackets are optional.

<script src="RGraph.common.core.js"></script>

<script>
    // Returns 9
    myArray = [3,2,5,4,9,7,8];
    max = RGraph.arrayMax(myArray);
</script>

 

Arrays

 

Strings

 

Numbers

 

Miscellaneous

 

Custom RGraph event related functions

 

Trigonometry functions

 

Other

These are functions which are less generic, and used to build the charts. You may still wish to use them however.

 

Creating your own chart type

If you want to create your own chart type using the RGraph system then you could use the Rect drawing object as a starting point. It has many of the methods that RGraph uses (eg .set, .get, .draw() ) and is also quite short and not overloaded with extraneous code.

 

The RGraph ObjectRegistry

The RGraph ObjectRegistry is new in March 2012 and it allows you to have multiple charts on a single canvas - both having dynamic features - such as the combined Bar and Line chart shown here.

You can combine any of the chart type in RGraph, such as Meters,gauges, Progress bars etc. Because it's a common combination, there's a special class for combined Bar and Line chart which you use like this:


<script>
    $(document).ready(function ()
    {
        var bar = new RGraph.Bar({
            id: 'cvs',
            data: [4,8,5,7,8,9],
            options: {
                labels: ['Alex','Doug','Charles','Nick','Michelle','Ali'],
                colors: ['#ffc'],
                tooltips: ['Alex','Doug','Charles','Nick','Michelle','Ali']
            }
        })
        
        var line = new RGraph.Line({
            id: 'cvs',
            data: [3,9,4,9,6,5],
            options: {
                tickmarks: 'endcircle',
                colors: ['black'],
                linewidth: 2,
                tooltips: ['1984','1985','1986','1987','1988','1989']
            }
        })
        
        // Create the combination object - this draws the chart for us
        var combo = new RGraph.CombinedChart(bar, line);
        combo.draw();
    }
</script>

You can have as many chart types as you want with the CombinedChart class, though the Bar should be the first one that you add to it. Because it's a common combination the CombinedChart class changes the line chart gutters 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:

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 do this is documented here.