在 Chart.js 条形图中显示数据值(版本 3)

Show data values in Chart.js bars (version 3)(在 Chart.js 条形图中显示数据值(版本 3))

本文介绍了在 Chart.js 条形图中显示数据值(版本 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于这个主题有很多答案(在 chart.js 中的条形顶部显示值),但这都是关于版本 2.x

There is a thread with many answers on this topic (Show values on top of bars in chart.js), but it's all about version 2.x

  • getDatasetMeta() 已被弃用:https://www.chartjs.org/docs/3.0.2/getting-started/v3-migration.html

数据标签"插件尚未移植到 3.x:https://github.com/chartjs/chartjs-plugin-datalabels

The "datalabels" plugin has not been ported to 3.x: https://github.com/chartjs/chartjs-plugin-datalabels

您找到任何可行的解决方案了吗?数据值如何显示在垂直条形图顶部(或水平条形图旁边)?

Have you found any working solutions? How can data values be displayed on top of vertical barcharts (or next to horizontal barcharts)?

推荐答案

您可以使用数据标签插件的测试版.

You can use the beta of the datalabels plugin.

文档:https://v2_0_0-rc_1--chartjs-plugin-datalabels.netlify.app/

脚本标签:<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc/dist/chartjs-plugin-datalabels.min.js"></script>

安装命令:npm i chartjs-plugin-datalabels@next

活生生的例子:

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
  var ctx = document.getElementById('myChart');
  
  Chart.register(ChartDataLabels); // first way of registering the plugin, registers them for all your charts
  
  var myChart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataLabels], // second way of registering plugin, register plugin for only this chart
    data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
        data: [12, 19, 3, 5, 2, 3],
        label: 'Advisor Closed MTD',
        backgroundColor: 'rgb(192,111,94)',
        barThickness: 25,
        datalabels: {
          color: '#FFCE56'
        }

      }],
    },
    options: {
      responsive: false,
      plugins: {
        datalabels: {
          anchor: 'end', // remove this line to get label in middle of the bar
          align: 'end',
          formatter: (val) => (`${val}%`),
          labels: {
            value: {
              color: 'blue'
            }
          }

        }
      }
    }
  });
</script>

这篇关于在 Chart.js 条形图中显示数据值(版本 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Chart.js 条形图中显示数据值(版本 3)

基础教程推荐