Chart.js: alternating background-color for ticks

1👍

This can be done with the chartjs-plugin-annotation library as shown in the runnable script below.

Detailed information about Box Annotations can be found here

const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

new Chart('chart', {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
        label: 'Dataset 1',
        backgroundColor: 'red',
        data: [95, 70, 55, -88, -64, 34, -55]
      },
      {
        label: 'Dataset 2',
        backgroundColor: 'green',
        data: [81, 58, 30, -91, -74, 20, -40]
      }
    ]
  },
  options: {
    plugins: {
      annotation: {
        annotations: labels
          .map((l, i) => ({
            drawTime: 'beforeDatasetsDraw',
            type: 'box',
            xScaleID: 'x',
            yScaleID: 'y',
            xMin: i - 0.5,
            xMax: i + 0.5,
            backgroundColor: 'rgba(128, 128, 128, 0.2)',
            borderColor: 'rgba(128, 128, 128, 0.4)',
            borderWidth: 1
          }))
          .filter((l, i) => !(i % 2))
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.2.2/chartjs-plugin-annotation.js"></script>
<canvas id="chart" width="300"></canvas>

Leave a comment