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

如何在Chart.js图表内部和鼠标悬停提示中显示百分比符号

Chart.js 显示百分比符号解决方案

图表内部标签显示百分比

在现有的datalabels配置中新增formatter回调函数,用于自定义标签输出内容:

plugins: {
  datalabels: {
    backgroundColor: function (context) {
      return context.dataset.backgroundColor;
    },
    borderRadius: 25,
    borderWidth: 3,
    color: "black",
    font: {
      weight: "bold"
    },
    padding: 6,
    // 新增格式化配置
    formatter: (value, context) => {
      // 场景1:原始数值为百分比数值(如30代表30%),直接拼接%
      return `${value}%`
      // 场景2:原始数值为小数占比(如0.3代表30%),可改为:
      // return `${Math.round(value * 100)}%`
      // 场景3:需要计算当前值占数据集总和的百分比:
      // const dataset = context.chart.data.datasets[context.datasetIndex]
      // const total = dataset.data.reduce((sum, val) => sum + val, 0)
      // const percent = Math.round((value / total) * 100)
      // return `${percent}%`
    }
  },

悬停提示显示百分比

修改现有tooltip的label回调逻辑,补全带百分号的数值输出:

tooltip: {
    callbacks: {
      label: (ttItem) => {
        // 可根据自身数值格式调整逻辑,以下为原始数值是百分比数值的示例
        return `${ttItem.label}: ${ttItem.parsed.y}%`
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:27:01