anychart

Filling a chart with a color above a specific Y value


I've been trying to fill a chart with color above certain Y value and I can't do it. What I tried to do is writing a condition that if the value is >3.5 that area of the chart will be filled with a different color.

splineSeries.fill(function() {
    if (this.value > 3.5)
    return '#d3f335 0.4'
    else
      return '#cdf0a7 0.6'})

However, this doesn't work for me as it fills the whole area of the chart which values are >3.5 and not only the area that it's above the line.

This is how that chunk of code is working in my chart.1

If you know how this can be solved I would really appreciate if you help me :)

Thanks!!


Solution

  • It does not seem AnyChart supports this kind of filling out of the box. You can however get creative with gradients:

      var cmin   = chart.getStat("yScalesMin");
      var cmax   = splineSeries.getStat('seriesMax');
      var cutoff = 3.5;
      
      splineSeries.fill({
        angle: 90,
        keys: [{
          color: '#cdf0a7',
          opacity: 0.6,
          offset: (cutoff-cmin) / (cmax-cmin)
        }, {
          color: '#d3f335',
          opacity: 0.4,
          offset: (cutoff-cmin) / (cmax-cmin)
        }],
        thickness: 3
      });
    

    Here's a working example:

        chart = anychart.area();
    
        var series = chart.area(generateRandomData());
    
        var cmin   = chart.getStat("yScalesMin");
        var cmax   = series.getStat('seriesMax');
        var cutoff = 3.5;
      
        series.fill({
          angle: 90,
          keys: [{
            color: '#cdf0a7',
            opacity: 0.6,
            offset: (cutoff-cmin) / (cmax-cmin)
          }, {
            color: '#d3f335',
            opacity: 0.4,
            offset: (cutoff-cmin) / (cmax-cmin)
          }],
          thickness: 3
        });
    
        chart.container("chart");
        chart.draw();
    
        function generateRandomData() {
          var data = [];
          for (let i=0; i<16; i++) {
            data.push({x:i, value:Math.random() * 7.5});
          }
          return data;
        }
    #chart {
      height: 400px;
    }
        <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
        <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-cartesian.min.js"></script>
        <div id="chart"></div>

    This should also work with charts with yScalesMin > 0