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

Chart.js v4图表标题与图例不显示问题求助

问题解决:饼图标题和图例不显示

问题原因

  • 未注册必要插件:Chart.js v4.x 开始要求手动注册所有用到的插件,你仅注册了ArcElement,但标题(Title)和图例(Legend)插件未注册,导致它们无法生效。
  • 组件参数传递错误:你把包含type、data、options的config对象直接传给了Pie组件的options属性,不符合react-chartjs-2的API规范。

修正后的代码

import React from 'react';
import { Pie } from 'react-chartjs-2';
import { Chart, ArcElement, Title, Legend } from 'chart.js';

// 注册所有需要用到的插件
Chart.register(ArcElement, Title, Legend);

const GenderRatio = () => {
  const data = {
    labels: ['Male', 'Female'],
    datasets: [
      {
        data: [60, 40],
        backgroundColor: ['#8F91C0', '#FF94C2'],
        hoverBackgroundColor: ['#36A2EB', '#FF6384'],
      },
    ],
  };

  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
        display: true
      },
      title: {
        display: true,
        text: 'Chart.js Pie Chart'
      }
    }
  };

  // 正确传递data和options属性
  return <Pie data={data} options={options} />;
};

export default GenderRatio;

另一种写法(直接传递完整配置)

如果偏好使用config对象,可直接将其传给Pie组件的chart属性:

// ... 其他代码不变
const config = {
  type: 'pie',
  data: data,
  options: options
};

return <Pie chart={config} />;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:55:05