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

如何让MUI5 Pie Chart图例实现展开与圆形标记效果?

解决MUI5 Pie Chart图例的自定义需求

下面是基于MUI内置组件实现你需求的完整方案,无需自定义图例组件:

1. 将图例标记改为圆形

直接在Legend组件的icon属性中,替换默认矩形为MUI内置的Circle图标:

import { Circle } from '@mui/icons-material';

// 应用在Legend组件中
<Legend
  icon={({ color }) => <Circle sx={{ fontSize: 12, color }} />}
  // 其他配置项
/>

2. 实现底部列排列+展开/收起功能

通过状态管理控制图例显示数量,结合Legend的布局配置实现列排列效果:

import { useState } from 'react';
import { PieChart, Pie, Cell, Legend } from '@mui/x-charts/PieChart';
import { Circle } from '@mui/icons-material';
import { Button, Box } from '@mui/material';

// 示例图表数据
const CHART_DATA = [
  { id: 'cat1', value: 35, label: '类别1' },
  { id: 'cat2', value: 25, label: '类别2' },
  { id: 'cat3', value: 20, label: '类别3' },
  { id: 'cat4', value: 10, label: '类别4' },
  { id: 'cat5', value: 7, label: '类别5' },
  { id: 'cat6', value: 3, label: '类别6' },
];

const DEFAULT_VISIBLE_ROWS = 2; // 默认显示2行

export default function CustomLegendPieChart() {
  const [showAllLegends, setShowAllLegends] = useState(false);

  // 计算可展示的图例项:按每行2个算,默认显示2行即4个
  const visibleItems = showAllLegends 
    ? CHART_DATA 
    : CHART_DATA.slice(0, DEFAULT_VISIBLE_ROWS * 2);

  return (
    <Box sx={{ width: '100%', maxWidth: 600, margin: '0 auto' }}>
      {/* 饼图主体:关闭自动渲染的图例 */}
      <PieChart
        series={[{ data: CHART_DATA, outerRadius: 100, innerRadius: 60 }]}
        legend={false}
      >
        {/* 为每个扇区分配颜色 */}
        {CHART_DATA.map((_, idx) => (
          <Cell key={`cell-${idx}`} fill={`hsl(${idx * 60}, 70%, 50%)`} />
        ))}
      </PieChart>

      {/* 手动控制的图例区域 */}
      <Box sx={{ marginTop: 2, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <Legend
          items={visibleItems.map((item, idx) => ({
            id: item.id,
            value: item.label,
            color: `hsl(${idx * 60}, 70%, 50%)`,
          }))}
          icon={({ color }) => <Circle sx={{ fontSize: 12, color }} />}
          // 配置布局:每行显示2个,实现两列排列效果
          layout={{ direction: 'row', justifyContent: 'center', maxItemsPerRow: 2 }}
        />

        {/* 展开/收起按钮 */}
        {CHART_DATA.length > DEFAULT_VISIBLE_ROWS * 2 && (
          <Button
            variant="text"
            onClick={() => setShowAllLegends(!showAllLegends)}
            sx={{ marginTop: 1 }}
          >
            {showAllLegends ? '收起' : '展开更多'}
          </Button>
        )}
      </Box>
    </Box>
  );
}

核心细节说明

  • 关闭饼图自带的legend自动渲染,手动使用Legend组件精确控制显示内容
  • 利用maxItemsPerRow设置每行显示的图例数量,轻松实现多列排列效果
  • 借助useState管理展开/收起状态,切换时更新要显示的图例项数组
  • 图例标记完全使用MUI内置的Circle组件替换,未引入自定义组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:30:24