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

react-chartjs-2如何设置X/Y轴刻度、图例标签字体为白色

问题原因

配置不生效有3个核心原因:

  • 配置语法和安装的react-chartjs-2版本不匹配:现有写法是Chart.js v2的旧语法,目前主流的v3/v4版本配置结构有破坏性变更,旧属性不会被识别
  • 只配置了Y轴刻度颜色,完全遗漏了X轴的刻度颜色设置
  • datasets里写的Color: "white"是无效属性,图例颜色不在数据集配置项里设置
修正方案

目前主流v3/v4版本(对应chart.js ≥3.0.0,react-chartjs-2 ≥3.0.0)直接用下面的完整代码替换即可:

const data = {
  labels: graph,
  datasets: [
    {
      label: "Appointment",
      data: appointment,
      backgroundColor: "#6c8bff",
      borderColor: "#6c8bff",
      borderWidth: 1,
    },
    {
      label: "Cancelled",
      backgroundColor: "red",
      borderColor: "red",
      borderWidth: 1,
      data: cancelled,
    },
  ],
};

const options = {
  // 图例配置移到plugins节点下
  plugins: {
    legend: {
      labels: {
        color: "white", // v3+版本字体颜色属性为color,不是旧版的fontColor
      },
    },
  },
  scales: {
    // v3+版本轴配置为对象格式,不再是数组
    x: {
      ticks: {
        color: "white", // X轴刻度设为白色
      },
    },
    y: {
      ticks: {
        color: "white", // Y轴刻度设为白色
        beginAtZero: true,
      },
    },
  },
};

return (
  <>
    <Bar data={data} options={options} />
  </>
);

如果你还在使用v2旧版本,只需要在原有options的scales节点下补充X轴配置即可,参考:

const options = {
  legend: {
    labels: {
      fontColor: "white",
    },
  },
  scales: {
    yAxes: [
      {
        ticks: {
          fontColor: "white",
          beginAtZero: true,
        },
      },
    ],
    // 补充X轴配置
    xAxes: [
      {
        ticks: {
          fontColor: "white",
        },
      },
    ],
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 18:03:16