HOWTO: Show a multi-color Line chart

Introduction

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 are now very easy for you to implement. The code for a chart of this type is shown below.

Remember that, whilst 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',
    xaxisTickmarksCount: 6,
    yaxis: false,
    textSize: 16,
    spline: true,
    shadow: false,
    marginInner: 0,
    backgroundGridVlinesCount: 6,
    tickmarksStyle:'dot',
    tickmarksSize:6,
    marginBottom: 10,
    marginTop: 10,
    marginRight: 5,
    backgroundGrid: false
};




// Draw the top, green part of the chart
line1 = 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.
//
line2 = new RGraph.Line({
    id: 'cvs',
    data: data,
    options: {
        ...options,
        colors: ['red'],
        filledColors: ['rgba(255,0,0,0.25)']
    }
}).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:

Note about margin sizing

When you use the tophalf bottomhalf lefthalf and righthalf clipping options then you need to keep in mind that they do just that and if you have unequal margin settings then the X-axis or Y axis will not be be in the center of the canvas. You will thus need to calculate the correct coordinate to use yourself. You can do this like so:

var y = ((myObj.canvas.height - myObj.get('marginTop') - myObj.get('marginBottom')) / 2) + myObj.get('marginTop')