如何在Matplotlib子图中添加X、Y组标签(仿JMP默认样式)
为Matplotlib共享轴子图矩阵添加JMP样式组标签
实现方案
Matplotlib没有内置的组标签功能,我们可以通过自定义画布文本标注+调整子图布局来复刻JMP的样式,让组标签位于整个子图矩阵的边缘中心位置,而非单个子图的轴标签。
步骤1:创建共享轴的子图矩阵
先初始化带共享X/Y轴的子图网格,示例用2行2列的布局:
import matplotlib.pyplot as plt # 创建共享X、Y轴的子图矩阵 fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(8, 6)) # 填充子图内容(示例) for i in range(2): for j in range(2): axes[i,j].plot([1,2,3], [i+j, i+j+1, i+j+2]) axes[i,j].set_xlabel("子图X标签") axes[i,j].set_ylabel("子图Y标签")
步骤2:调整布局预留组标签空间
用subplots_adjust增加画布边缘的空白,避免组标签和子图内容重叠:
# 上下左右留出足够空间放置组标签 plt.subplots_adjust(top=0.85, bottom=0.15, left=0.15, right=0.85)
步骤3:添加全局组标签
调用fig.text()在画布的指定位置添加组标签,通过坐标控制居中对齐,颜色设为红色匹配需求:
# X轴组标签:底部中心位置 fig.text(0.5, 0.02, "X轴组标签", ha='center', va='center', fontsize=12, fontweight='bold', color='red') # Y轴组标签:左侧中心位置,垂直旋转 fig.text(0.02, 0.5, "Y轴组标签", ha='center', va='center', fontsize=12, fontweight='bold', color='red', rotation='vertical')
步骤4:细节优化(可选)
如果子图轴标签和组标签间距太近,可以调整子图标签的内边距:
# 调整子图轴标签的间距 for ax in axes.flat: ax.xaxis.labelpad = 10 ax.yaxis.labelpad = 10
完整运行代码
import matplotlib.pyplot as plt # 创建共享轴子图矩阵 fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(8, 6)) # 绘制示例数据 for i, row in enumerate(axes): for j, ax in enumerate(row): ax.plot([1, 2, 3], [i*2 + j, i*2 + j +1, i*2 + j +2]) ax.set_xlabel("单个子图X标签") ax.set_ylabel("单个子图Y标签") ax.set_title(f"子图 ({i+1}, {j+1})") # 调整布局空间 plt.subplots_adjust(top=0.85, bottom=0.15, left=0.15, right=0.85) # 添加JMP样式的红色组标签 fig.text(0.5, 0.01, "X轴全局组标签", ha='center', va='center', fontsize=14, fontweight='bold', color='red') fig.text(0.01, 0.5, "Y轴全局组标签", ha='center', va='center', fontsize=14, fontweight='bold', color='red', rotation='vertical') plt.show()
内容的提问来源于stack exchange,提问作者Kevin Daugherty
相关产品推荐
相关产品推荐

