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

如何调整Material UI BarChart的Y轴宽度及样式设置

解决@mui/x-charts BarChart的Y轴配置问题

针对你遇到的yAxisWidth不生效问题,新版本@mui/x-charts(v6及以上)已不再使用顶级的yAxisWidth属性,需在yAxis配置数组中为每个Y轴设置width属性。以下是满足你三个需求的完整实现方案:

需求实现细节

1. 调整Y轴宽度以显示副标题

在yAxis配置对象中添加width属性,设置足够容纳副标题的数值,同时可通过label.style优化显示效果:

yAxis: [
  {
    width: 120, // 自定义Y轴宽度
    label: {
      text: '销售额统计', // 副标题文本
      style: { fontSize: 12, whiteSpace: 'normal' } // 确保文本换行显示
    }
  }
]

2. 将Y轴单位改为R$(雷亚尔)

通过tickFormatter函数为每个刻度值添加R$前缀,同时适配巴西本地化数值格式:

tickFormatter: (value) => {
  return `R$ ${value.toLocaleString('pt-BR')}`;
}

3. 对齐Y轴数值与悬停tooltip的格式

@mui/x-charts的tooltip默认采用本地化数值格式,我们只需让Y轴的tickFormatter复用相同逻辑即可。若需自定义tooltip格式,可同步配置tooltip.formatter:

tooltip: {
  formatter: (params) => ({
    label: params.label,
    value: `R$ ${params.value.toLocaleString('pt-BR')}`
  })
}

完整代码示例

import { BarChart } from '@mui/x-charts';

const chartData = [
  { category: 'Produto A', value: 15600 },
  { category: 'Produto B', value: 89200 },
  { category: 'Produto C', value: 45700 }
];

export default function CustomizedBarChart() {
  return (
    <BarChart
      width={650}
      height={400}
      series={[{ data: chartData.map(item => item.value) }]}
      xAxis={[{ data: chartData.map(item => item.category), scaleType: 'band' }]}
      yAxis={[
        {
          width: 120,
          label: { text: '总销售额', style: { fontSize: 12 } },
          tickFormatter: (value) => `R$ ${value.toLocaleString('pt-BR')}`
        }
      ]}
      tooltip={{
        formatter: (params) => ({
          label: chartData[params.dataIndex].category,
          value: `R$ ${params.value.toLocaleString('pt-BR')}`
        })
      }}
    />
  );
}

额外注意事项

  • 确保使用@mui/x-charts的最新稳定版本,旧版本轴配置逻辑存在差异;
  • 若副标题仍显示不全,可进一步调整width数值或label.style的字体大小、换行属性;
  • 多Y轴场景下,只需在yAxis数组中添加对应配置对象即可分别设置。

内容的提问来源于stack exchange,提问作者Renan França

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:22:20