在chart.js中每列的条形图顶部显示值

8wtpewkr  于 2024-01-07  发布在  Chart.js
关注(0)|答案(1)|浏览(335)

我已经尝试了很多,以显示在字符顶部的值,但我不能这样做,请你能帮助我与此我也添加插件来显示数据。

  1. <canvas id="myChart" width="200" height="100" aria-label="Hello ARIA World" role="img"></canvas>
  2. <script>
  3. const ctx = document.getElementById('myChart');
  4. console.log({{sales_performance|safe}})
  5. new Chart(ctx, {
  6. type: 'bar',
  7. data: {
  8. labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  9. datasets: [{
  10. label: 'Sales',
  11. data: [1, 10, 10, 11, 1, 10, 10, 11, 1, 10, 11, 16],
  12. borderWidth: 1
  13. }]
  14. },
  15. options: {
  16. scales: {
  17. y: {
  18. display: false, // Hide the y-axis label
  19. beginAtZero: true
  20. }
  21. },
  22. plugins: {
  23. datalabels: {
  24. color: 'black', // Set the color of the data labels
  25. font: {
  26. weight: 'bold'
  27. },
  28. formatter: function(value, context) {
  29. return value; // Display the value on the bars
  30. }
  31. }
  32. }
  33. }
  34. });
  35. </script>

字符串
我想在每个条形列的顶部显示值。

6fe3ivhb

6fe3ivhb1#

这是一个常见的错误,因为库没有注册,所以 chartjs-plugin-datalabels 无法工作。您必须按照文档中的说明注册库。
要将数据标签定位在条形图的顶部,您需要在dataLabels数组的每个对象中添加datalabels属性。您可以阅读定位配置。

  1. datasets: [
  2. {
  3. ...
  4. datalabels: {
  5. align: 'top',
  6. anchor: 'end',
  7. },
  8. }
  9. ]

字符串
完整代码:

  1. new Chart(ctx, {
  2. type: 'bar',
  3. data: {
  4. labels: [
  5. 'Jan',
  6. 'Feb',
  7. 'Mar',
  8. 'Apr',
  9. 'May',
  10. 'Jun',
  11. 'July',
  12. 'Aug',
  13. 'Sep',
  14. 'Oct',
  15. 'Nov',
  16. 'Dec',
  17. ],
  18. datasets: [
  19. {
  20. label: 'Sales',
  21. data: [1, 10, 10, 11, 1, 10, 10, 11, 1, 10, 11, 16],
  22. borderWidth: 1,
  23. datalabels: {
  24. align: 'top',
  25. anchor: 'end',
  26. },
  27. },
  28. ],
  29. },
  30. options: {
  31. scales: {
  32. y: {
  33. display: false, // Hide the y-axis label
  34. beginAtZero: true,
  35. },
  36. },
  37. plugins: {
  38. datalabels: {
  39. color: 'black', // Set the color of the data labels
  40. font: {
  41. weight: 'bold',
  42. },
  43. formatter: function (value, context) {
  44. return value; // Display the value on the bars
  45. },
  46. },
  47. },
  48. },
  49. plugins: [ChartDataLabels],
  50. });


Demo @ StackBlitz

展开查看全部

相关问题