Chart.js Line chart with different fill color for negative point - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Chart.js Line chart with different fill color for negative point

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>chart.js 2.0</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.1/Chart.bundle.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from w  ww  . ja  v a 2  s . c om*/
Chart.defaults.NegativeTransparentLine = Chart.helpers.clone(Chart.defaults.line);
Chart.controllers.NegativeTransparentLine = Chart.controllers.line.extend({
  update: function() {
    var min = Math.min.apply(null, this.chart.data.datasets[0].data);
    var max = Math.max.apply(null, this.chart.data.datasets[0].data);
    var yScale = this.getScaleForId(this.getDataset().yAxisID);
    var top = yScale.getPixelForValue(max);
    var zero = yScale.getPixelForValue(0);
    var bottom = yScale.getPixelForValue(min);
    var ctx = this.chart.chart.ctx;
    var gradient = ctx.createLinearGradient(0, top, 0, bottom);
    var ratio = Math.min((zero - top) / (bottom - top), 1);
    gradient.addColorStop(0, 'rgba(75,192,192,0.4)');
    gradient.addColorStop(ratio, 'rgba(75,192,192,0.4)');
    gradient.addColorStop(ratio, 'rgba(0,0,0,0)');
    gradient.addColorStop(1, 'rgba(0,0,0,0)');
    this.chart.data.datasets[0].backgroundColor = gradient;
    return Chart.controllers.line.prototype.update.apply(this, arguments);
  }
});
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx, {
  type: 'NegativeTransparentLine',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First dataset",
      strokeColor: "rgba(60,91,87,1)",
      pointColor: "rgba(60,91,87,1)",
      pointStrokeColor: "#58606d",
      data: [65, 59, 65, -10, 56, -55, 40],
    }]
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart"></canvas>  
   </body>
</html>

Related Tutorials