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

MUI堆叠条形图自定义标签实现求助:顶部标签与底部图标

MUI堆叠条形图添加自定义顶部标签与底部图标解决方案

一、添加堆叠顶部总数值标签

MUI X Charts底层基于Recharts,默认barLabel仅支持单个分段标签,要实现顶部总标签,需手动计算堆叠总和后,通过Custom组件定位渲染:

  1. 预处理数据,计算每个X轴项的堆叠总和:
const data = [
  { name: '类别1', 数值1: 30, 数值2: 20, 数值3: 50 },
  { name: '类别2', 数值1: 40, 数值2: 10, 数值3: 50 },
];
// 生成带总和的数据集
const dataWithTotal = data.map(item => ({
  ...item,
  total: item.数值1 + item.数值2 + item.数值3,
}));
  1. 在图表中嵌入Custom组件渲染顶部标签:
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Custom } from '@mui/x-charts';

<BarChart
  width={600}
  height={300}
  data={dataWithTotal}
  series={[
    { dataKey: '数值1', stackId: 'group', fill: '#8884d8' },
    { dataKey: '数值2', stackId: 'group', fill: '#82ca9d' },
    { dataKey: '数值3', stackId: 'group', fill: '#ffc658' },
  ]}
>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  {/* 自定义顶部总标签 */}
  <Custom
    content={({ coordinates }) => {
      return dataWithTotal.map((item, index) => {
        const x = coordinates[index].x;
        // 上移15px避免标签贴在条形顶部
        const y = coordinates[index].y - 15;
        return (
          <text
            key={index}
            x={x}
            y={y}
            textAnchor="middle"
            fontSize={14}
            fontWeight="bold"
          >
            {item.total}
          </text>
        );
      });
    }}
  />
  <Bar />
</BarChart>

二、在堆叠底部内部添加图标

通过Cell组件给底部堆叠段嵌入图标,搭配foreignObject实现SVG内渲染HTML图标:

  1. 导入MUI图标:
import { ShoppingCart } from '@mui/icons-material';
  1. 给底部堆叠段绑定Cell渲染图标:
<BarChart
  width={600}
  height={300}
  data={data}
  series={[
    { dataKey: '数值1', stackId: 'group', fill: '#8884d8' },
    { dataKey: '数值2', stackId: 'group', fill: '#82ca9d' },
    { dataKey: '数值3', stackId: 'group', fill: '#ffc658' },
  ]}
>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  {/* 底部堆叠段嵌入图标 */}
  <Bar dataKey="数值1" stackId="group">
    {data.map((_, index) => (
      <Cell key={index}>
        <foreignObject
          x="10"
          y="10"
          width="40"
          height="40"
        >
          <ShoppingCart style={{ color: '#fff', fontSize: 24 }} />
        </foreignObject>
      </Cell>
    ))}
  </Bar>
  <Bar dataKey="数值2" stackId="group" />
  <Bar dataKey="数值3" stackId="group" />
</BarChart>

若需要图标在条形内居中,可通过计算条形宽高动态调整位置:

<foreignObject
  x={(coordinates[index].width - 40) / 2}
  y={(coordinates[index].height - 40) / 2}
  width="40"
  height="40"
>
  <ShoppingCart style={{ color: '#fff', fontSize: 24 }} />
</foreignObject>

coordinates可通过图表onLayout回调或Custom组件获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:42:32