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

如何优化React(mui/x-charts)数据图表布局?品牌堆叠异常求助

修复MUI X Charts堆叠柱状图布局问题

要解决品牌堆叠效果不理想的问题,核心是显式开启柱状图的堆叠模式,同时优化布局适配容器,具体调整如下:

关键修复步骤

  • 给每个系列配置相同的stack属性:MUI X的BarChart默认不会自动堆叠,需要让所有需要堆叠的系列共享同一个stack标识,图表才会将它们垂直堆叠。
  • 优化X轴带宽:调整bandwidth参数让柱子更紧凑,避免分散。
  • 自适应容器宽度:将图表宽度设为100%,适配Grid的响应式布局,避免固定宽度导致的挤压变形。

修改后的代码

<Grid container spacing={2}>
  {datasGraphBar != undefined ? datasGraphBar.map((graph, index) => (
    <Grid xs={12} md={6} key={index} className={'text-center'}>
      <Typography variant="h6">
        {graph.title}
      </Typography>
      <div className={'text-center'}>
        <BarChart
          xAxis={[{data: xAxis, scaleType: 'band', bandwidth: 0.8}]}
          // 给每个系列添加统一的stack标识,开启堆叠
          series={graph.datas.map(series => ({...series, stack: 'brandGroup'}))}
          width='100%' // 自适应容器宽度
          height={300}
        />
      </div>
    </Grid>
  )) : ''}
  {datasGraphLines != undefined ? datasGraphLines.map((graph, index) => (
    <Grid xs={12} md={6} key={index} className={'text-center'}>
      <Typography variant="h6">
        {graph.title}
      </Typography>
      <div className={'text-center'}>
        <LineChart
          xAxis={[{data: xAxis, scaleType: 'point'}]}
          series={graph.datas}
          width='100%'
          height={300}
        />
      </div>
    </Grid>
  )) : ''}
</Grid>

额外说明

如果graph.datas中存在不需要堆叠的系列,可针对性地给需要堆叠的系列设置stack属性,不同stack值的系列会分开独立显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:05:30