admin管理员组

文章数量:1394611

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() has been deprecated: .0.2/getting-started/v3-migration.html

  • The "datalabels" plugin has not been ported to 3.x:

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

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() has been deprecated: https://www.chartjs/docs/3.0.2/getting-started/v3-migration.html

  • The "datalabels" plugin has not been ported to 3.x: https://github./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)?

Share Improve this question asked Jun 1, 2021 at 12:43 CharlesMCharlesM 5712 gold badges7 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You can use the beta of the datalabels plugin.

Documentation: https://v2_0_0-rc_1--chartjs-plugin-datalabelslify.app/

Script tag: <script src="https://cdn.jsdelivr/npm/[email protected]/dist/chartjs-plugin-datalabels.min.js"></script>

Install mand: npm i chartjs-plugin-datalabels@next

Live example:

<script src="https://cdn.jsdelivr/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr/npm/[email protected]"></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>

本文标签: javascriptShow data values in Chartjs bars (version 3)Stack Overflow