如何在chartJS中为堆积条形/折线图添加数据标签

zlwx9yxi  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(235)

我尝试将数据标签添加到chartJS中的堆叠条形图/折线图中,特别是在折线图区域。因为值没有与Y轴对齐,所以我想使用chartJS数据标签插件来显示折线图顶部的值,只是为了在打印出来时更好地澄清。我尝试的是:

  1. # 1 putting into config
  2. const config = {
  3. type: 'line',
  4. data: data,
  5. options: {
  6. plugins: {
  7. datalabels: {
  8. anchor: 'end',
  9. align: 'top',
  10. formatter: function(value, context) {
  11. return GetValueFormatted(value);
  12. },
  13. borderRadius: 4,
  14. color: 'white',
  15. font: {
  16. weight: 'bold'
  17. },
  18. formatter: Math.round,
  19. padding: 6
  20. },
  21. title: {
  22. display: true,
  23. text: 'Menu Performance Chart'
  24. },
  25. },
  26. scales: {
  27. y: {
  28. stacked: true
  29. }
  30. }
  31. },
  32. };
  33. # 2 putting into specific dataset
  34. const data = {
  35. labels: labels,
  36. datasets: [{
  37. label: 'Sub Total Sales (RM)',
  38. data: [
  39. '111',
  40. '22',
  41. '31',
  42. '12',
  43. '71',
  44. '110',
  45. '22',
  46. ],
  47. borderColor: 'rgb(255, 99, 132)',
  48. backgroundColor: 'rgba(255, 99, 132, 0.2)',
  49. stack: 'combined',
  50. type: 'bar'
  51. },
  52. {
  53. label: 'Total Amount Sold',
  54. data: [
  55. '11',
  56. '2',
  57. '3',
  58. '1',
  59. '7',
  60. '10',
  61. '2',
  62. ],
  63. borderColor: 'rgb(255, 159, 64)',
  64. backgroundColor: 'rgba(255, 159, 64, 0.2)',
  65. stack: 'combined',
  66. datalabels: {
  67. color: '#FFCE56'
  68. }
  69. },
  70. ]
  71. };

我甚至同时尝试了两种,看看有没有结果。有没有人能协助我这方面的工作?提前感谢。
下面是我在JSFiddle中的代码演示:https://jsfiddle.net/4gat7rzs/4/

mtb9vblg

mtb9vblg1#

插件未注册。请参阅doc:https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#registration
您应该将数据标签插件示例添加到图表配置中:

  1. const config = {
  2. type: 'line',
  3. data: data,
  4. plugins: [ChartDataLabels], // <- MUST BE ADDED
  5. options: {
  6. ....

相关问题