Chartjs-Can you do regions in line charts with Chart.js?

2👍

You can achieve this, using a ChartJS plugin called – chartjs-plugin-annotation

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var ctx = c.getContext('2d');
var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'Statistics',
         data: [3, 1, 2, 5, 4],
         backgroundColor: 'rgba(0, 119, 204, 0.2)',
         borderColor: 'rgba(0, 119, 204, 0.8)',
         borderWidth: 2,
         fill: false,
         lineTension: 0
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      },
      annotation: {
         annotations: [{
            type: 'box',
            drawTime: 'beforeDatasetsDraw',
            id: 'region-1',
            xScaleID: 'x-axis-0',
            yScaleID: 'y-axis-0',
            xMin: 'Jan',
            xMax: 'May',
            yMin: 2.5,
            yMax: 4.5,
            backgroundColor: 'rgba(200,230,201,0.5)'
         }, {
            type: 'box',
            drawTime: 'beforeDatasetsDraw',
            id: 'region-2',
            xScaleID: 'x-axis-0',
            yScaleID: 'y-axis-0',
            xMin: 'Jan',
            xMax: 'May',
            yMin: 0,
            yMax: 2,
            backgroundColor: 'rgba(255,205,210 ,0.5)'
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdn.rawgit.com/chartjs/chartjs-plugin-annotation/master/chartjs-plugin-annotation.min.js"></script>
<canvas id="c"></canvas>

Leave a comment