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

如何修改Chart.js饼图切片内计数数字的字体颜色

修改Chart.js饼图切片内数字的字体颜色

要修改饼图切片内的计数数字字体颜色,你需要用到chartjs-plugin-datalabels插件(原生Chart.js并未内置切片内数据标签功能),具体配置如下:

  1. 先确保已安装并引入插件:

    • npm安装:npm install chartjs-plugin-datalabels
    • 或通过CDN引入:<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
  2. 在你的options配置中添加datalabels插件配置,通过color属性设置字体颜色:

// 如果使用模块引入,先导入插件
import ChartDataLabels from 'chartjs-plugin-datalabels';

const options = {
    plugins: {
      legend: {
        display: true,
        labels: {
          usePointStyle: true,
          pointStyle: "rectRounded",
        },
      },
      title: {
        display: false,
        text: "Use of App",
      },
      tooltip: {
        callbacks: {
          label: function (context) {
            const label = context.label || "";
            const value = context.parsed;
            const total = context.dataset.data.reduce(
              (a, b) => a + b,
              0
            );
            const percentage = calculatePercentage(value, total);
            return `${label}: ${value} (${percentage})`;
          },
        },
      },
      // 配置数据标签插件
      datalabels: {
        color: '#ffffff', // 这里设置你需要的字体颜色,支持十六进制、RGB、颜色名称
        font: {
          weight: 'bold', // 可选:设置字体粗细
          size: 14        // 可选:设置字体大小
        },
        formatter: (value) => value // 自定义显示内容,这里直接显示数值
      }
    },
    // 注册插件(全局注册过的话可省略)
    plugins: [ChartDataLabels]
  };
  1. 如果需要给不同切片设置不同颜色,可以将color设为函数:
datalabels: {
  color: (context) => {
    // 根据切片索引返回对应颜色
    const colorList = ['#000', '#fff', '#ff4444', '#4CAF50'];
    return colorList[context.dataIndex % colorList.length];
  },
  // 其他配置...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:10:16