Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highchart Area Range chart with gradient that follows the line

The following is an Area Range chart which has a gradient.

http://jsfiddle.net/gXpHH/1/

What I want to do is have the gradient follow the curve, so that the color at any point along the bottom line is the same, and it ends at the same color when it reaches the top line. I am pretty sure that this is not currently an option in highcharts, but I just wanted to see if anyone has run into this before. Here is the code that currently generates the gradient:

series: [{
            name: "Shade",
            fillColor: {
                linearGradient: [0, 0, 0, 300],
                stops: [
                    [0, "#4572A7"],
                    [1, "rgba(2,0,0,0)"]
                ]
            },
            data: [
                [0, 14733, 18890],
                [1, 16583, 21642],
                //... rest here
                [10, 42417, 61955]
            ]
    }]

Thanks

Note: this is not the same as Gradient Fill on Line Chart (Highcharts) since I need the gradient to follow the curve

like image 749
Justin Bicknell Avatar asked Feb 08 '13 20:02

Justin Bicknell


1 Answers

The difficulty is the granularity: Highcharts draws one single SVG path for the series' points, and associates that one path with the gradient. If your series data is relatively linear however, the following approximation might be useful. See the jsfiddle that I've created:

Assuming that your series data is not static, my demo includes two series and a function that, for each series, attempts to dynamically create the linearGradient that comes closest to your requirement:

function getLinearGradient(series) {
    var lastY0=null, lastY1=null, maxY0=null, maxY1=null;
    $.each(series.data, function(key,value) {
        maxY0 = Math.max(value[1],maxY0);
        maxY1 = Math.max(value[2],maxY1);
        lastY0 = value[1];
        lastY1 = value[2];
    });
    var firstY0 = series.data[0][2],
        firstY1 = series.data[0][2]
    ;
    var minY0=maxY0, minY1=maxY1;
    $.each(series.data, function(key,value) {
        minY0 = Math.min(value[1],minY0);
        minY1 = Math.min(value[2],minY1);
    });
    var minY = minY0,
        maxY = maxY1,
        heightY = maxY - minY
    ;        
    var gradient = {
            x1: 10 + ( ((firstY0-minY) / heightY) * 80 ) + "%",
            y1: "10%",
            x2: 10 + ( ((lastY1-minY) / heightY) * 80 ) + "%",
            y2: "90%"
    };
    return gradient;
};

Of course, this approach is not a full-blown solution and only useful if you're dealing with data that approximately follows a linear curve. Here's the jsfiddle

like image 81
marty Avatar answered Nov 02 '22 18:11

marty