Chartjs-ChartJS – change color a part of label

1πŸ‘

βœ…

This answer deals with a similar question but the proposed solution only works for Chart.js v2.

Please take a look at the amended code below that works with Chart.js v3.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      let ctx = chart.ctx;
      let xAxis = chart.scales.x;
      let yAxis = chart.scales.y;
      chart.data.labels.forEach((l, i) => {
        let labelTokens = l.split('(');        
        let rotation = chart.options.scales.x.ticks.rotation * -Math.PI / 180;
        let x = xAxis.getPixelForValue(l);      
        ctx.font = '12px Arial';        
        if (labelTokens.length == 2) {
          ctx.save();
          let width = ctx.measureText(labelTokens.join(' ')).width;
          ctx.translate(x, yAxis.bottom + 10);
          ctx.rotate(rotation);
          ctx.fillText(labelTokens[0], -width, 0);
          ctx.restore();
        }
        ctx.save();
        let labelEnd = '(' + labelTokens[labelTokens.length - 1];
        let width = ctx.measureText(labelEnd).width;
        ctx.translate(x, yAxis.bottom + 10);
        ctx.rotate(rotation);      
        ctx.fillStyle = 'red';
        ctx.fillText(labelEnd, -width, 0);
        ctx.restore();
      });
    }
  }],
  data: {
    labels: ['ABC(1level)', 'ABC(2level)'],
    datasets: [{
      label: 'Result',
      data: [30, 59],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)'],
      borderWidth: 1
    }]
  },
  options: {
    maintainAspectRatio: false,
    layout: {
      padding: {
        bottom: 60
      }
    },
    scales: {
      x: {
        ticks: {
          display: false,
          rotation: 40
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<div style="width: 160px; min-height: 200px;">
  <canvas id="myChart"></canvas>
</div>

Leave a comment