About
RGraph is a JavaScript charts library based on HTML5 SVG and canvas. RGraph is mature (over 15 years old) and has a wealth of features making it an ideal choice to show charts on your website.

More »

 

Download
Get the latest version of RGraph (version 6.17) from the download page. There's also older versions available, minified files and links to cdnjs.com hosted libraries.

More »

 

License
RGraph can be used for free under the GPL or if that doesn't suit your situation there's an inexpensive (£99) commercial license available.

More »

Internal API documentation

Overview

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:

<script src="RGraph.common.core.js"></script>
<script src="RGraph.bar.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 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 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:

this.context.beginPath();
this.context.rect(5, 5,100,100);
this.context.strokeStyle = 'black';
this.context.fillStyle = 'red';
this.context.stroke();
this.context.fill();

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:

context.path('b r 0 0 100 100 f red');

That represents the following code:

context.fillStyle = 'red'
context.beginPath();
context.rect(0,0,100,100);
context.fill();

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);
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:

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.

Chart type Data variable(s)
Activity obj.min, obj.max, obj.value
Bar obj.data
Bi-polar obj.left, obj.right
Donut This is now a variant of the Pie chart
Fuel obj.min, obj.max, obj.value
Funnel obj.data
Gantt See the documentation
Gauge obj.min, obj.max, obj.value
Horizontal Bar obj.data
Horseshoe obj.min, obj.max, obj.value
Horizontal Progress obj.min, obj.max, obj.value
Line obj.original_data3
Meter obj.min, obj.max, obj.value
Odometer obj.min, obj.max, obj.value
Pie obj.data
Radar obj.original_data
Rose obj.data
Radial Scatter obj.data
Semi-circular Progress obj.min, obj.max, obj.value
Scatter obj.data2
Segmented obj.min, obj.max, obj.value
Thermometer obj.min, obj.max, obj.value
Vertical Progress obj.min, obj.max, obj.value
Waterfall 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

Warning
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>
Warning
RGraph has ajax helper functions that minimise type conversion hassles. You can read more about these functions in the ajax HOWTO guide.

Note: You could also use jquery for ajax queries:

<script>
    $.get('/getData.html', function (data)
    {
        // Use the RGraph function $p() to show the returned data
        $p(data);
    });
</script>
        

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

  1. Get your new data from the server (with an ajax request for example).
  2. Set the data on 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 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).

obj.set({
    marginLeft:   35,
    marginRight:  35,
    marginTop:    35,
    marginBottom: 35
});

obj.get('marginLeft');
obj.get('marginRight');
obj.get('marginTop');
obj.get('marginBottom');

References that are 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 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:

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 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()

RGraph functions

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 functions

GET functions

Clipping functions

Notice
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.

Arrays

Strings

Numbers

Miscellaneous

Custom RGraph event-related functions

Trigonometry functions

Other

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

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 Meters, gauges, Progress bars etc. Because it's a common combination, there's a special class for 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, though 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()

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.