[Chartjs]-Chartjs change the specific label color in x axis in callback function

2👍

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 with the desired styles underneath each bar.

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 = value == 60 ? 'red' : 'blue';
        ctx.fillText(value, x, yAxis.bottom + 17);
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First Dataset",
      data: [60, 59, 80, 81, 60, 55, 40],
      fill: false,
      backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
      borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        bottom: 20
      }
    },
    scales: {
      xAxes: [{
        ticks: {
          display: false
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment