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

Pandas分组子图绘图:如何为整体添加通用X/Y轴标签

为Pandas分组子图添加全局X/Y轴标签

我来帮你解决这个问题!你已经通过分组和unstack绘制出3行1列的子图,想要给整个图表添加统一的X轴、Y轴标签,而非逐个子图单独设置,这里有两种实用的方法:

方法1:利用Figure的supxlabel/supylabel(推荐,matplotlib 3.4+)

这个方法是matplotlib较新版本提供的原生全局标签功能,操作简单且布局更合理:

import pandas as pd
import matplotlib.pyplot as plt

# 构造你的DataFrame
data = {
    'groupcol': ['A', 'B', 'C', 'A', 'C', 'A', 'B'],
    'value': [10, 12, 10, 10, 17, 11, 15]
}
df = pd.DataFrame(data, index=[1,2,3,4,5,6,7])

# 绘制子图并获取子轴对象
axs = df.groupby([df.index,'groupcol']).mean()['value'].unstack().plot(subplots=True, layout=(3,1))
# 从任意一个子轴获取整个图表的Figure对象
fig = axs[0].figure

# 添加全局X/Y轴标签
fig.supxlabel('你的全局X轴名称', fontsize=12)
fig.supylabel('你的全局Y轴名称', fontsize=12)

# 调整布局,避免标签和子图内容重叠
plt.tight_layout()
plt.show()

方法2:使用fig.text手动定位(兼容旧版matplotlib)

如果你的matplotlib版本低于3.4,没有supxlabel和supylabel,可以通过手动定位文本的方式添加全局标签:

import pandas as pd
import matplotlib.pyplot as plt

# 构造DataFrame(同上)
data = {
    'groupcol': ['A', 'B', 'C', 'A', 'C', 'A', 'B'],
    'value': [10, 12, 10, 10, 17, 11, 15]
}
df = pd.DataFrame(data, index=[1,2,3,4,5,6,7])

# 绘制子图
axs = df.groupby([df.index,'groupcol']).mean()['value'].unstack().plot(subplots=True, layout=(3,1))
fig = axs[0].figure

# 添加全局X轴标签(居中放在整个图表底部)
fig.text(0.5, 0.02, '你的全局X轴名称', ha='center', fontsize=12)
# 添加全局Y轴标签(垂直居中放在整个图表左侧)
fig.text(0.02, 0.5, '你的全局Y轴名称', va='center', rotation='vertical', fontsize=12)

plt.tight_layout()
plt.show()

两种方法的核心都是先获取整个图表的Figure对象,再通过Figure的方法添加全局标签,这样就能避免逐个子图设置的繁琐,让整个图表的标签风格统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:04:31