Gradient line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Gradient line chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  w w w  .  j a  v a  2  s  .  c o  m*/
var gradientLinePlugin = {
  // Called at start of update.
  beforeUpdate: function(chartInstance) {
    if (chartInstance.options.linearGradientLine) {
      // The context, needed for the creation of the linear gradient.
      var ctx = chartInstance.chart.ctx;
      // The first (and, assuming, only) dataset.
      var dataset = chartInstance.data.datasets[0];
      // Calculate min and max values of the dataset.
      var minValue = Number.MAX_VALUE;
      var maxValue = Number.MIN_VALUE;
      for (var i = 0; i < dataset.data.length; ++i) {
        if (minValue > dataset.data[i])
          minValue = dataset.data[i];
        if (maxValue < dataset.data[i])
          maxValue = dataset.data[i];
      }
      // Calculate Y pixels for min and max values.
      var yAxis = chartInstance.scales['y-axis-0'];
      var minValueYPixel = yAxis.getPixelForValue(minValue);
      var maxValueYPixel = yAxis.getPixelForValue(maxValue);
      // Create the gradient.
      var gradient = ctx.createLinearGradient(0, minValueYPixel, 0, maxValueYPixel);
      // A kind of red for min.
      gradient.addColorStop(0, 'rgba(231, 18, 143, 1.0)');
      // A kind of blue for max.
      gradient.addColorStop(1, 'rgba(0, 173, 238, 1.0)');
      // Assign the gradient to the dataset's border color.
      dataset.borderColor = gradient;
      // Uncomment this for some effects, especially together with commenting the `fill: false` option below.
      // dataset.backgroundColor = gradient;
    }
  }
};
Chart.pluginService.register(gradientLinePlugin);
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["First", "Second", "Third", "Fourth", "Fifth"],
    datasets: [{
      label: 'My Sample Dataset',
      data: [20, 30, 50, 10, 40],
      // No curves.
      tension: 0,
      // No fill under the line.
      fill: false
    }],
  },
  options: {
    // Option for coloring the line with a gradient.
    linearGradientLine: true,
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          max: 100,
          stepSize: 20
        }
      }]
    }
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart" width="400" height="200"></canvas>  
   </body>
</html>

Related Tutorials