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

如何在Matplotlib分组柱状图的分组标签与柱状图间添加Men/Women轴标签?

为分组柱状图添加子X轴标签

原Matplotlib分组柱状图代码已实现基础的分组展示,若需要在每个主分组(G1-G5)标签与对应柱状图之间,为Men、Women的柱子分别添加x轴子标签,可参考以下修改后的代码:

import matplotlib.pyplot as plt
import numpy as np

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # 主分组标签的位置
width = 0.35  # 单根柱子的宽度

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

# 主坐标轴基础设置
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x, labels)
ax.legend()

# 为柱子添加数值标签
ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)

# 创建次级x轴用于显示子标签
ax2 = ax.twiny()
# 设置次级x轴的刻度位置:对应每个分组下Men、Women柱子的中心
ax2.set_xticks(np.repeat(x, 2) + np.tile([-width/2, width/2], len(labels)))
# 设置子标签内容
ax2.set_xticklabels(['Men', 'Women'] * len(labels))
# 调整次级x轴位置,使其位于主x轴下方(靠近柱状图)
ax2.spines['bottom'].set_position(('outward', 30))
# 隐藏次级x轴的顶部边框,优化视觉效果
ax2.spines['top'].set_visible(False)

fig.tight_layout()

plt.show()

关键改动说明:

  • 调用ax.twiny()创建共享y轴的次级x轴,专门承载子标签
  • 利用np.repeat和np.tile生成子标签的精准位置,与每根柱子的中心对齐
  • 通过set_position调整次级x轴的摆放位置,让子标签处于主分组标签和柱状图之间
  • 隐藏次级x轴的顶部边框,避免冗余元素干扰视觉

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:18:14