如何设置Matplotlib坐标轴几何宽高,实现等尺寸子图?
解决Matplotlib 2×2子图尺寸不一致问题
问题描述
需要制作四个尺寸一致的2×2矩阵子图,其中两个子图带有第二y轴,且其中一个轴标题为希腊字母,导致子图尺寸不均、观感差。同时希望子图独立,方便添加单独标签。
疑问点:
- 是否可直接以英寸为单位设置单个坐标轴长度,保证尺寸完全一致?
- 有没有定义原点坐标的选项避免布局偏移?
- 是否可强制单个绘图为正方形且尺寸相等?
测试代码:
fig, ax = plt.subplots(figsize=(3,3)) ax2 = ax.twinx() ax.plot([1,2],[3,4]) ax2.plot([3,4],[100,1000]) ax.set_box_aspect(1) ax2.set_box_aspect(1) plt.show()
解决方案
1. 强制所有子图为正方形(最推荐)
利用constrained_layout自动适配布局,同时给所有坐标轴(包括双轴)设置正方形比例,确保尺寸一致:
import matplotlib.pyplot as plt # 创建2×2子图,开启约束布局自动调整间距 fig, axs = plt.subplots(2, 2, figsize=(8, 8), constrained_layout=True) # 给所有子图设置正方形比例 for ax in axs.flat: ax.set_box_aspect(1) # 第一个带希腊字母轴标题的双轴子图 ax_top_left = axs[0, 0] ax_top_left_twin = ax_top_left.twinx() ax_top_left.plot([1, 2], [3, 4]) ax_top_left_twin.plot([3, 4], [100, 1000]) ax_top_left_twin.set_ylabel(r'$\alpha$') # 希腊字母轴标题 ax_top_left_twin.set_box_aspect(1) # 双轴必须同步设置正方形比例 # 第二个双轴子图 ax_bottom_right = axs[1, 1] ax_bottom_right_twin = ax_bottom_right.twinx() ax_bottom_right.plot([1, 3], [2, 5]) ax_bottom_right_twin.plot([2, 4], [50, 200]) ax_bottom_right_twin.set_box_aspect(1) # 剩余两个单轴子图示例 axs[0, 1].plot([1, 2], [5, 7]) axs[1, 0].plot([3, 5], [1, 4]) plt.show()
2. 精确控制坐标轴尺寸(英寸单位)
通过add_axes手动定义每个子图的位置和尺寸(单位为画布比例,可换算为英寸),完全掌控布局:
import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 8)) # 8×8英寸的画布 # 每个正方形子图的尺寸(2英寸),换算为画布比例:2/8=0.25 subplot_size = 0.25 # 子图之间的间距(1英寸),换算为比例:1/8=0.125 gap = 0.125 # 逐个创建子图,位置参数为[左, 下, 宽, 高] ax1 = fig.add_axes([0.1, 0.6 + gap, subplot_size, subplot_size]) ax1_twin = ax1.twinx() ax1.plot([1, 2], [3, 4]) ax1_twin.plot([3, 4], [100, 1000]) ax1_twin.set_ylabel(r'$\alpha$') ax2 = fig.add_axes([0.1 + subplot_size + gap, 0.6 + gap, subplot_size, subplot_size]) ax2.plot([1, 2], [5, 7]) ax3 = fig.add_axes([0.1, 0.1, subplot_size, subplot_size]) ax3.plot([3, 5], [1, 4]) ax4 = fig.add_axes([0.1 + subplot_size + gap, 0.1, subplot_size, subplot_size]) ax4_twin = ax4.twinx() ax4.plot([1, 3], [2, 5]) ax4_twin.plot([2, 4], [50, 200]) # 强制所有坐标轴为正方形 for ax in [ax1, ax1_twin, ax2, ax3, ax4, ax4_twin]: ax.set_box_aspect(1) plt.show()
3. 避免布局偏移的关键细节
- 必须给双轴的
ax2也设置set_box_aspect(1):否则双轴会打破正方形比例 - 开启
constrained_layout=True:自动适配轴标题、刻度等元素的空间,避免因文字长度差异导致偏移 - 统一轴标题和刻度的字体大小:减少不同子图间的空间占用差异
内容的提问来源于stack exchange,提问作者Jan Kinder
相关产品推荐
相关产品推荐

