chart.js v4截断比例/标签

bhmjp9jg  于 2023-03-02  发布在  Chart.js
关注(0)|答案(1)|浏览(174)

类似的问题在过去也曾被问过,但最终是针对较旧版本的Chart.js。这些问题的公认答案不起作用。我有一个类似的图表:

此图表的代码如下:

  1. new Chart(
  2. document.getElementById("chart-01"), {
  3. type: 'bar',
  4. data: {
  5. labels: ["Test loooooong 1", "Test loooooong 2", "Test loooooong 3"],
  6. datasets: [{ data: [574.48, 140.93, 64.37]}]
  7. },
  8. options: {
  9. scales: {
  10. y: {
  11. ticks: {
  12. callback: function(value) {
  13. return '$ ' + value;
  14. }
  15. }
  16. },
  17. // x : {
  18. // ticks : {
  19. // callback : function(value, index, ticks) { return value.split(0,8)+'...';}
  20. // }
  21. // }
  22. },
  23. plugins: {
  24. legend: {
  25. display: false
  26. }
  27. }
  28. }
  29. }
  30. );
  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.1/chart.umd.js" integrity="sha512-vCUbejtS+HcWYtDHRF2T5B0BKwVG/CLeuew5uT2AiX4SJ2Wff52+kfgONvtdATqkqQMC9Ye5K+Td0OTaz+P7cw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  2. <canvas id="chart-01" width="500" height="600"></canvas>

我尝试截断x轴上8个字符后的名称,并添加一个'...',因此,如果我使用注解代码块:

  1. x : {
  2. ticks : {
  3. callback : function(value, index, ticks) { return value.split(0,8)+'...';}
  4. }
  5. }

我收到错误消息:

    • 未捕获(承诺中)的TypeError:值。split不是函数**

同样,如果我只使用值,而不使用分割,我会得到数字,但不会得到标签名称。
这些链接指向对我不起作用的解决方案。
https://stackoverflow.com/a/39537545/3408158https://stackoverflow.com/a/44418430/3408158
我哪里做错了?

ebdffaop

ebdffaop1#

要获取/更改标签的值,必须使用函数getLabelForValue

split是不正确的函数,您需要使用substring

  • (x一e一f一x)*
    • 以下是输入示例代码的所有修复:**
  1. new Chart(document.getElementById("chart"), {
  2. type: 'bar',
  3. data: {
  4. labels: ["Test looooong 1", "Test looooong 2", "Test looooong 3"],
  5. datasets: [{ data: [574.48, 140.93, 64.37]}]
  6. },
  7. options: {
  8. scales: {
  9. y: {
  10. ticks: { callback: value => `$ ${value }` }
  11. },
  12. x: {
  13. ticks: {
  14. callback: function(value){
  15. let newLabel = this.getLabelForValue(value)
  16. .substring(0,8) + '...';
  17. return newLabel;
  18. }
  19. }
  20. }
  21. }
  22. }
  23. });
  1. <script src="//cdn.jsdelivr.net/npm/chart.js"></script>
  2. <div class="chart" style="height:184px; width:350px;">
  3. <canvas id="chart" ></canvas>
  4. </div>
    • 信息:**上述解决方案不起作用,因为据我所知,它们基于chartjs Verion 2.0+,从那时起,chartjs库发生了重大变化。
展开查看全部

相关问题