为条形图添加标签:chartjs

Yige Song

我正在使用 chartjs 3.5.1 创建条形图,我是 chartjs 的新手。我想为条形图中的每个条形添加值标签。

我已经查看了一些相关的答案,但它们要么太旧,要么太复杂而无法实现。

以下是预期的结果,请注意,非手写部分是我所实现的。 在此处输入图片说明

代码如下:

let chart2 = new Chart('chart2', {
  type: 'bar',
  data: {
    labels: ["a", "b", "c", "d"],
    datasets: [{
      data: [500, 400, 300, 200],
      }]
  },
  options: {
    indexAxis: 'y',
    plugins: {
      title: {
        display: true,
        text: "Graph"
      },
      legend: {
        display: false,
      }
    },
    scales: {
      y: {
        grid: {
          display: false
        },
      },
      x: {
        grid: {
          display: false
        }
      }
    }
  },

});

真的很感谢你的帮助!

乌明德

您可以使用chartjs-plugin-datalabels图书馆。

首先你必须注册插件,然后你可以在里面定义所需的选项options.plugins.datalabels

请查看您修改后的代码,看看它是如何工作的。

Chart.register(ChartDataLabels);
new Chart('chart2', {
  type: 'bar',
  data: {
    labels: ["a", "b", "c", "d"],
    datasets: [{
      data: [500, 400, 300, 200],
    }]
  },
  options: {
    indexAxis: 'y',
    layout: {
      padding: {
        right: 60
      }
    },
    plugins: {
      title: {
        display: true,
        text: "Graph"
      },
      legend: {
        display: false,
      },
      datalabels: {
        color: 'blue',
        anchor: 'end',
        align: 'right',
        labels: {
          title: {
            font: {
              weight: 'bold'
            }
          }
        }
      }
    },
    scales: {
      y: {
        grid: {
          display: false
        },
      },
      x: {
        grid: {
          display: false
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="chart2" height="100"></canvas>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章