Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing chartjs tick colours

Tags:

chart.js

Does anyone have any ideas on how I can change the colours of the ticks on the y axis of a bar chart dynamically?

I can change the colour of all the ticks but can't seem to find a way to change them individually like the picture below.

Any tips would be appreciated.

bar chart

like image 554
P_J Avatar asked Feb 15 '21 22:02

P_J


1 Answers

In the upcomming release of the V3 version of the lib you can do this with the scriptable options by passing a function to the color key in the tick config instead of a color.

const colors = ['red', 'blue', 'yellow', 'green'];
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
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      x: {
        ticks: {
          color: (c) => {
            return colors[c.index % colors.length]
          }
        }
      },
      y: {
        ticks: {
          color: (c) => {
            return colors[c.index % colors.length]
          }
        }
      }
    }
  }
}

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.0.0-beta.10/chart.js" integrity="sha512-7igYTuENB1pHNsZ/SyzMYrcJAmRCk084yVOsxNNCQAdX1wSYvCeBOgSOMC6wUdKMO76kCJNOpW4jY3UW5CoBnA==" crossorigin="anonymous"></script>
</body>
like image 191
LeeLenalee Avatar answered Oct 16 '22 09:10

LeeLenalee