动态改变chartjs刻度颜色 [英] Dynamically changing chartjs tick colours

查看:16
本文介绍了动态改变chartjs刻度颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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>

这篇关于动态改变chartjs刻度颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆