You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何在Chart.js 2的柱状图柱子顶部添加数值标签?

Solution for Adding Top Labels to Chart.js 2 Bar Chart

Hey there! You're already on the right track using the chartjs-plugin-datalabels plugin—you just need to adjust its configuration to get the labels positioned correctly on top of your bars (matching your "Resultado mês" style example). Here's the refined code and breakdown:

Updated JavaScript Code

window.onload = function() { 
  var ctx = document.getElementById('ps-chart').getContext('2d'); 
  var data = { 
    labels: ["Jan/18", "Fev/18", "Mar/18", "Abr/18", "Mai/18", "Jun/18", "Jul/18", "Ago/18", "Set/18", "Out/18", "Nov/18", "Dez/18"], 
    datasets: [
      { 
        label: "Entradas", 
        data: [650, 590, 800, 810, 560, 550, 400, 800, 810, 560, 550, 400], 
        backgroundColor: '#33bfff' 
      }, 
      { 
        label: "Saídas", 
        data: [-280, -480, -400, -190, -860, -270, -900, -400, -190, -860, -270, -900], 
        backgroundColor: '#E75A5B' 
      } 
    ] 
  };

  var myChart = new Chart(ctx, { 
    type: 'bar', 
    data: data, 
    options: { 
      responsive: false, 
      plugins: { 
        datalabels: { 
          // Format value as Brazilian Real currency
          formatter: function(value, context) { 
            return value.toLocaleString('pt-BR', { 
              style: 'currency', 
              currency: 'BRL' 
            }); 
          },
          // Position labels at the top of each bar (handles positive/negative automatically)
          position: 'top',
          // Center labels horizontally over bars
          align: 'center',
          // Style labels for readability
          color: '#222',
          font: {
            weight: 'bold',
            size: 11
          },
          // Add small offset to prevent label from touching the bar
          offset: 4
        } 
      }, 
      legend: { 
        display: true, 
      }, 
      tooltips: { "enabled": false }, 
      scales: { 
        yAxes: [{ 
          display: false, 
          ticks: { display: false } 
        }], 
        xAxes: [{ 
          stacked: true, 
          barPercentage: 1.2, 
          gridLines: { display: false } 
        }] 
      } 
    } 
  }); 
}

Key Changes Explained

  • Position & Alignment: The position: 'top' setting automatically places labels at the end of each bar—positive values get labels above the bar, negative values (like your "Saídas" dataset) get labels below the bar, which matches the natural top of each bar segment. align: 'center' ensures labels sit perfectly over the bar width.
  • Label Styling: Added color, font.weight, and font.size to match the bold, readable style of your example. Adjust the size value if you need bigger/smaller text.
  • Offset: The offset: 4 adds a small gap between the label and the bar, preventing overlap and improving visual clarity.

Verify Plugin Loading

Your existing HTML already includes the correct plugin versions (Chart.js 2.7.2 and chartjs-plugin-datalabels 0.3.0), which are compatible. Just keep that script setup as-is:

<script src="https://github.com/chartjs/Chart.js/releases/download/v2.7.2/Chart.bundle.min.js"></script> 
<script src="https://github.com/chartjs/chartjs-plugin-datalabels/releases/download/v0.3.0/chartjs-plugin-datalabels.min.js"></script> 
<canvas id="ps-chart" style="width:100%"></canvas>

This will replace your temporary HTML/CSS solution with a native Chart.js implementation that maintains consistency with your chart's behavior.

内容的提问来源于stack exchange,提问作者Alex Novelli

火山引擎 最新活动