[Chartjs]-How to set color of Chart.js tick label based on tick value โ€“ negative values red

1๐Ÿ‘

โœ…

You can define the scriptable option scales.x.ticks.color as an array of colors that depend on the corresponding data value each. The following definition for example shows red tick labels for every bar of a value less than 10.

scales: {
  x: {
    ticks: {
      color: data.map(v => v < 10 ? 'red' : undefined)
    }
  }
}

For further information, consult Tick Configuration from the Chart.js documentation.

Please take a look at below runnable code and see how it works.

const data = [4, 12, 5, 13, 15, 8];

new Chart('myChart', {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F'],
    datasets: [{
      label: 'Dataset',
      data: data,
    }]
  },
  options: {
    responsive: false,
    scales: {
      x: {
        ticks: {
          color: data.map(v => v < 10 ? 'red' : undefined)
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="myChart" height="180"></canvas>

Leave a comment