You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Chart.js在条形图后添加带MWp后缀的数值文本

问题解决:Chart.js水平条形图添加数值标签不显示

问题核心原因

  1. 重复plugins配置导致覆盖:你在Chart选项中写了两个独立的plugins键,JavaScript对象中重复的键会被后者覆盖,导致自定义的afterDatasetsDraw插件根本没被加载。
  2. 水平条形坐标计算错误:水平条形图里,bar._model.x是条形的左边缘位置,直接用这个值加偏移会让文字出现在条形内部甚至左侧,自然看不到效果。

修复步骤

  1. 合并Plugins配置:把datalabels和自定义插件合并到同一个plugins对象中,避免覆盖。
  2. 修正文本位置:
    • X坐标:用bar._model.x + bar._model.width + 10,确保文字在条形右侧(bar._model.width是条形的实际宽度)
    • Y坐标:调整为bar._model.y + bar._model.height / 2 + 4,让文字垂直居中(适配字体基线)
  3. 可选优化Canvas样式:原HTML中Canvas的style="width:5%"可能导致图表过窄,建议移除该行内样式,让JS设置的宽度完全生效。

修正后的完整JavaScript代码

var labels = ["18 Monate"];
var data1 = [229]; // Data for the first bars
var data2 = [1175]; // Data for the second bars
var barColors1 = ["#348200"]; // Fill color for the first bar
var barColors2 = ["#98CB35"]; // Fill color for the second bar
var borderColors1 = ["#A3D33A"]; // Border color for the first bar
var borderColors2 = ["#348200"]; // Border color for the second bar
var valueRange = [0, data1[0] + data2[0]]; // Min and max values for the x-axis
var canvas = document.getElementById('myChart'); // Canvas for graphs
var projektclusterDiv = document.querySelector('.projektcluster'); // Projektcluster Div

// Function to create and return the chart
function createChart(callback) {
  // Adjust the canvas width to match the "projektcluster" div width
  if (projektclusterDiv) {
    canvas.width = projektclusterDiv.offsetWidth - 50; // Adjusting for some padding
    console.log('Width of the "projektcluster" div:', projektclusterDiv.offsetWidth, 'pixels');
    console.log('New canvas width:', canvas.width, 'pixels');
  } else {
    console.log('No element with class "projektcluster" found.');
  }

  // Create a new chart instance
  var chart = new Chart(canvas, {
    type: "horizontalBar",
    data: {
      labels: labels,
      datasets: [
        {
          label: 'Graph1-18Monate',
          backgroundColor: barColors1,
          borderColor: borderColors1,
          borderWidth: 2,
          data: data1
        },
        {
          label: 'Graph2-18Monate',
          backgroundColor: barColors2,
          borderColor: borderColors2,
          borderWidth: 2,
          data: data2
        }
      ]
    },
    options: {
      responsive: false, // Make sure the chart is not responsive to fit the fixed dimensions
      maintainAspectRatio: false,
      legend: { display: false }, // Hides the legend
      scales: {
        xAxes: [{
          ticks: { 
            display: false, 
            min: valueRange[0], // Use the first element of valueRange as the min value
            max: valueRange[1]  // Use the second element of valueRange as the max value
          },
          gridLines: {
            display: false,
            drawOnChartArea: false,
            drawTicks: false,
            color: "transparent"
          },
          drawBorder: true,
          borderColor: "transparent"
        }],
        yAxes: [{
          gridLines: {
            display: false,
          },
          drawBorder: true,
          borderColor: "transparent"
        }]
      },
      // 合并plugins配置,避免覆盖
      plugins: {
        datalabels: {
          display: false
        },
        // 自定义afterDatasetsDraw插件
        afterDatasetsDraw: function(chart) {
          var ctx = chart.chart.ctx;
          chart.data.datasets.forEach(function(dataset, i) {
            var meta = chart.getDatasetMeta(i);
            meta.data.forEach(function(bar, index) {
              var data = dataset.data[index];
              ctx.fillStyle = 'black';
              ctx.font = 'bold 12px Arial';
              // 修正坐标:水平条形右边缘+偏移,垂直居中
              var xPos = bar._model.x + bar._model.width + 10;
              var yPos = bar._model.y + bar._model.height / 2 + 4;
              ctx.fillText(data + ' MWp', xPos, yPos);
            });
          });
        }
      }
    }
  });

  // Execute the callback after the chart is rendered
  chart.update();
  if (callback) callback(chart);
  return chart;
}

// Initial chart creation
createChart();

可选HTML调整

将Canvas的行内样式修改为:

<canvas id="myChart" height="50"></canvas>

内容的提问来源于stack exchange,提问作者Raphael Zimmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:12:11