Tullochgorum
Tullochgorum

Reputation: 531

Highcharts: how to assign different colours to a spline depending on positive or negative slope?

I'm evaluating Highcharts for a project and it seems to be missing a built-in feature I would need.

For a spline, I need to assign one colour if the slope is positive, and another if it is negative, like this:

enter image description here

Before I invest the time in learning the API, it would be helpful to know if this is doable. A working example would be much appreciated.

Upvotes: 0

Views: 452

Answers (1)

ppotaczek
ppotaczek

Reputation: 39099

You can use dynamically calculated zones, for example:

events: {
  load: function() {
    let points = this.series[0].points,
      zones = [],
      color;

    function addZone(value, color) {
      zones.push({
        value: value,
        color: color
      });
    }

    points.forEach(function(p, i) {
      if (points[i - 1]) {
        if (p.y >= points[i - 1].y) {

          if (color && color !== 'green') {
            addZone(points[i - 1].x, 'red');
          }

          color = 'green';

        } else if (p.y <= points[i - 1].y) {
          if (color && color !== 'red') {
            addZone(points[i - 1].x, 'green');
          }

          color = 'red';
        }
      }

      addZone(p.x, color);
    });

    this.series[0].update({
      zones: zones
    });
  }
}

Live demo: http://jsfiddle.net/BlackLabel/jmckag4q/1/

API Reference: https://api.highcharts.com/highcharts/series.line.zones

Upvotes: 1

Related Questions