HOWTO: Show a multi-color Line chart

Showing a Line chart with different colors based on a certain threshold is not an uncommon request. It got a lot easier in version 6.07 thanks to the new RGraph.clipTo.start() function. This function allows you to restrict drawing to half of what would normally be drawn. You then clip to the other half of the canvas, draw another chart with similar options and the same data but different colors.

[No canvas support]

Showing dual-color line charts has, in the past, involved a fair amount of custom coding. Now, however, the amount of code involved has been reduced to a single line that is easy to understand.

This means that dual-color Line charts like the one shown here is now very easy for you to implement. The code for this particular chart is shown below.

Remember that, whilst the example shown above and the common usage is based around a Line chart, the clipping functions are not tied to any particular chart so they can be used with any chart of your choosing.


Example code

//
// This is the data that's displayed on the chart. Both Line
// chart objects use it.
//
data = [
    4,8,6,3,5,2,4,2,-2,-3,-5,-9,
    -4,3,8,4,6,3,5,1,4,-2,-4,-5
];

//
// These options are used for the first chart (the top half)
// and then reused (with a few changes - like changing
// the color to red) for the second, bottom chart
//
options = {
    colors: ['green'],
    xaxisPosition: 'center',
    yaxis: false,
    spline: true,
    shadow: false,
    marginInner: 0,
    backgroundGridVlinesCount: 6,
    xaxisTickmarksCount: 6,
    tickmarksStyle:'dot',
    tickmarksSize:4,
    marginBottom: 5,
    marginTop: 5,
    marginRight: 5
};

//
// Draw the top, green part of the chart
//
new RGraph.Line({
    id: 'cvs',
    data: data,
    options: options
}).on('beforedraw', function (obj)
{
    // Start clipping to the top half of the canvas
    RGraph.clipTo.start(obj, 'tophalf');

}).on('draw', function (obj)
{
    // Finish clipping
    RGraph.clipTo.end(obj);
}).draw();

//
// Now draw the bottom, red part of the chart. Use the options
// that are defined above but with a few changes. The options
// can be combined here by using the ES6 spread (...) operator.
//
new RGraph.Line({
    id: 'cvs',
    data: data,
    options: {
        ...options,
        yaxisScale: false,
        colors: ['red']
    }
}).on('beforedraw', function (obj)
{
    // Start clipping to the bottom half of the canvas
    RGraph.clipTo.start(obj, 'bottomhalf');

}).on('draw', function (obj)
{
    // Finish clipping
    RGraph.clipTo.end(obj);
}).draw();

Documentation for the function

The RGraph.clipTo.start() function is quite versatile and can take many options - these are detailed in the API documentation . There are also three demo pages in the download archive which you can look through - these are: