[Chartjs]-X-axis multiple colored label for bar chart using chart.js

3👍

You can make use of the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw text of the same color as the corresponding bar.

chart.data.labels.forEach((l, i) => {
  var value = chart.data.datasets[0].data[i];
  var x = xAxis.getPixelForValue(l);        
  ctx.fillStyle = chart.data.datasets[0].backgroundColor[i];
  ctx.fillText(l, x, yAxis.bottom + 17);
});

When drawing your own tick labels, you need to instruct Chart.js not to display the default labels. This can be done through the following definition inside the chart options.

scales: {
  xAxes: [{
    ticks: {
      display: false
    }
  }], 

You also need to define some padding for the bottom of the chart, otherwise you won’t see your custom tick labels.

layout: {
  padding: {
    bottom: 20
  }
},

Please take a look at the following sample code that illustrates how to change the labels on the x-axis depending on the values.

new Chart('myChart', {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      ctx.textAlign = 'center';
      ctx.font = '12px Arial';
      chart.data.labels.forEach((l, i) => {
        var value = chart.data.datasets[0].data[i];
        var x = xAxis.getPixelForValue(l);        
        ctx.fillStyle = chart.data.datasets[0].backgroundColor[i];
        ctx.fillText(l, x, yAxis.bottom + 17);
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ["-3", "-2", "-1", "0", "+1", "+2", "+3"],
    datasets: [{
      label: "My First Dataset",
      data: [60, 59, 80, 81, 60, 55, 40],
      fill: false,
      backgroundColor: ['rgba(245,88,97,1)', 'rgba(245,88,97,1)', 'rgba(245,88,97,1)',     'rgba(145,151,163,1)', 'rgba(70,180,220,1)', 'rgba(70,180,220,1)', 'rgba(70,180,220,1)'],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        bottom: 20
      }
    },
    scales: {
      xAxes: [{
        ticks: {
          display: false
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
canvas {
  max-width: 300px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>

Leave a comment