Chartjs-Chart.JS Alternate background color for xAxis

1👍

Alternate background may be created with the use of chartjs-plugin-annotation.

Please have a look at the code snippet below that has been derived from the example code provided by the contributors of chartjs-plugin-annotation.

This code works with Chart.js 2.6.0 and it still produces a script error that may be ignored. Unfortunately I couldn’t make it work with the newest version of Chart.js (currently 2.9.3) yet and I don’t have time now to further investigate.

const labels = ["January", "February", "March", "April", "May", "June", "July"];
const annotations = [];
for (let i = 0; i < labels.length; i++) {
  if (i % 2 == 0) {
    annotations.push({
      drawTime: "beforeDatasetsDraw",
      type: "box",
      xScaleID: "x-axis-0",
      yScaleID: "y-axis-0",
      xMin: labels[i],
      xMax: labels[i + 1],
      backgroundColor: "rgba(128, 128, 128, 0.5)",
      borderColor: "rgb(128, 128, 128)",
      borderWidth: 1
    });
  }
};

new Chart('chart', {
  type: "bar",
  data: {
    labels: labels,
    datasets: [{
        label: "Dataset 1",
        backgroundColor: 'red',
        data: [95, 70, 55, -88, -64, 34, -55],
        categoryPercentage: 1,
        barPercentage: 0.8
      },
      {
        label: "Dataset 2",
        backgroundColor: 'green',
        data: [81, 58, 30, -91, -74, 20, -40],
        categoryPercentage: 1,
        barPercentage: 0.9
      }
    ]
  },
  options: {
    responsive: true,
    tooltips: {
      mode: "index",
      intersect: true
    },
    annotation: {
      annotations: annotations
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="chart" height="90"></canvas>

0👍

we can use annotation plugin to do this

import annotationPlugin from "chartjs-plugin-annotation";
import {Chart} from 'chart.js';
Chart.register(annotationPlugin);

this code will add a box to our chart

{
  type: 'box', #type of draw
  drawTime: 'beforeDraw', #this will decide background or foreground
  yMin: 5, #value min on y axis
  yMax: 10, #value max on y axis
  borderColor: 'rgb(242, 244, 248, 0.9)', #border color of the box
  borderWidth: 1, #boarder width for box
  backgroundColor: '#F2F4F8', #colour of the box
}

Out of this codeenter image description here

refer to this post here on how to do this: https://medium.com/@omi10859/alternative-background-lines-in-chartjs-a626ce4d3bcb

Leave a comment