Chartjs-Chart.js: how to set multiple color to tick of y axes if > or < 0

0👍

You will have to update to v3 of the lib, then you can make use of the scriptable options like this:

  options: {
    scales: {
      y: {
        ticks: {
          color: (tick) => (tick.tick.value < 0 ? 'red' : tick.tick.value > 0 ? 'green' : '#666')
        }
      }
    }
  }

Live example:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [-12, 19, 3, -5, 2, 3],
      borderWidth: 1,
      borderColor: 'red',
      backgroundColor: 'red'
    }]
  },
  options: {
    scales: {
      y: {
        ticks: {
          color: (tick) => (tick.tick.value < 0 ? 'red' : tick.tick.value > 0 ? 'green' : '#666')
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.0/chart.js"></script>
</body>

Leave a comment