Chart.js自定义各个垂直轴标签

2ul0zpep  于 2023-02-04  发布在  Chart.js
关注(0)|答案(1)|浏览(241)

我正在使用Chart.js创建一个水平条形图,如下所示。y轴有三个标签:A、B、C。如何单独设置这些垂直标签的样式?例如,我可能希望将其中一个或两个标签加粗和/或设置为红色。
我看了这个答案:https://stackoverflow.com/a/65463614/3851085。然而,这是x轴的解。对于y轴,需要不同的解来计算每个标签的x像素。
该代码片段使用的是较旧版本的Chart.js,但实际上我使用的是最新版本。

  1. <html>
  2. <head>
  3. <title>Horizontal Bars</title>
  4. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
  5. </head>
  6. <body>
  7. <div>
  8. <canvas id="canvas" height="100"></canvas>
  9. </div>
  10. <script>
  11. window.onload = function() {
  12. var ctx = document.getElementById('canvas').getContext('2d');
  13. window.myBar = new Chart(ctx, {
  14. type: 'horizontalBar',
  15. data: {
  16. labels: ['A', 'B', 'C'],
  17. datasets: [{
  18. data: [[1, 3], [4, 5], [2, 6]],
  19. backgroundColor: 'lightblue'
  20. }]
  21. },
  22. options: {
  23. responsive: true,
  24. legend: {
  25. display: false,
  26. }
  27. }
  28. });
  29. };
  30. </script>
  31. </body>
  32. </html>
mmvthczy

mmvthczy1#

文档对此并不清楚,但是您可以在options中使用arrays来配置标签。
下面是您的代码,经过重构以兼容Chart. js 4.2.0

  1. window.onload = function() {
  2. var ctx = document.getElementById('myChart').getContext('2d');
  3. window.myBar = new Chart(ctx, {
  4. type: 'bar',
  5. data: {
  6. labels: ['A', 'B', 'C'],
  7. datasets: [{
  8. data: [[1, 3], [4, 5], [2, 6]],
  9. backgroundColor: 'lightblue'
  10. }]
  11. },
  12. options: {
  13. responsive: true,
  14. indexAxis: 'y',
  15. scales: {
  16. y: {
  17. ticks: {
  18. color: ['#ff0000', '#000000', '#000000'],
  19. font: {
  20. weight: ['bold', 'bold', 'normal']
  21. }
  22. }
  23. }
  24. },
  25. plugins: {
  26. legend: {
  27. display: false
  28. }
  29. }
  30. }
  31. });
  32. };
  1. .chart-container {
  2. position: relative;
  3. height: 90vh;
  4. }
  1. <script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.0"></script>
  2. <div class="chart-container">
  3. <canvas id="myChart"></canvas>
  4. </div>
展开查看全部

相关问题