enable plotting if values are present in line charts? - Javascript highcharts

Javascript examples for highcharts:Line Chart

Description

enable plotting if values are present in line charts?

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Highcharts Demo</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
   </head> 
   <body> 
      <script src="https://code.highcharts.com/highcharts.js"></script> 
      <script src="https://code.highcharts.com/highcharts-more.js"></script> 
      <script src="https://code.highcharts.com/modules/exporting.js"></script> 
      <script src="https://code.highcharts.com/modules/export-data.js"></script> 
      <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div> 
      <script type="text/javascript">
function addPlotbands(chart) {/*w  ww . j  av a 2  s  .  c  o  m*/
  let series = chart.series
  let yMin = chart.yAxis[0].getExtremes().min;
  let yMax = chart.yAxis[0].getExtremes().max;
  for (let i = 0; i < series[0].data.length; i++) {
    let allAboveZero = true;
    let allBelowZero = true;
    for (let j = 0; j < chart.series.length; j++) {
      if (series[j].data[i].y >= 0) {
        allBelowZero = false;
      } else {
        allAboveZero = false;
      }
    }
    if (allAboveZero) {
      addCustomElement(chart, i, 0, yMax)
    } else if (allBelowZero) {
      addCustomElement(chart, i, yMin, 0)
    } else {
      addCustomElement(chart, i, yMin, yMax)
    }
  }
}
function addCustomElement(chart, x, yMin, yMax) {
  let yAxis = chart.yAxis[0]
  let xAxis = chart.xAxis[0]
  chart.customRect.push(chart.renderer.rect(
      xAxis.toPixels(x - 0.5, false), //Leftmost pixel
      yAxis.toPixels(yMax, false), //Topmost pixel
      xAxis.toPixels(x + 0.5, false) - xAxis.toPixels(x - 0.5, false), //Width
      yAxis.toPixels(yMin, false) - yAxis.toPixels(yMax, false) //Height
    )
    .attr({
      'stroke-width': 2,
      fill: 'gray',
      zIndex: -1
    })
    .add());
}
Highcharts.chart('container', {
  chart: {
    type: 'column',
    events: {
      load: function() {
        this.customRect = []
        addPlotbands(this);
      },
      redraw: function() {
        if (this.customRect) {
          for (let i = 0; i < this.customRect.length; i++) {
            this.customRect[i].destroy();
          }
          this.customRect = []
          let chart = this;
          setTimeout(function() {
            addPlotbands(chart)
          }, 100);
        }
      }
    }
  },
  title: {
    text: 'Column chart with negative values'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'],
  },
  credits: {
    enabled: false
  },
  series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2, -3],
  }, {
    name: 'Jane',
    data: [2, -2, -2, 2, 1, -1]
  }, {
    name: 'Joe',
    data: [3, 4, 4, -2, 5, -2]
  }]
});

      </script>  
   </body>
</html>

Related Tutorials