如何在Python Matplotlib中设置不同图形的相同坐标轴尺寸
解决Matplotlib中不同图表坐标轴(Axes)尺寸一致的问题
当设置相同figsize但绘制不同数据时,Matplotlib会自动调整坐标轴(Axes)位置以容纳标签、刻度等元素,导致实际绘图区域的宽高不一致。以下是几种可靠的解决方案:
方法1:使用constrained_layout(推荐)
这是Matplotlib 3.0+自带的智能布局系统,会自动调整布局,确保所有图表的Axes尺寸一致,同时避免元素重叠。
import matplotlib.pyplot as plt # 生成第一个图表 fig1, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(3.5, 3), constrained_layout=True) ax1.plot([0.1, 0.2, 0.3]) ax1.set_ylabel('Y', weight='bold') ax1.set_xlabel('X', weight='bold') # 生成第二个图表 fig2, ax2 = plt.subplots(nrows=1, ncols=1, figsize=(3.5, 3), constrained_layout=True) ax2.plot([1, 2, 3]) ax2.set_ylabel('Y', weight='bold') ax2.set_xlabel('X', weight='bold') plt.show()
方法2:手动固定Axes位置
直接指定Axes在画布中的相对位置和尺寸,彻底避免自动调整带来的差异。参数格式为[left, bottom, width, height],所有值都是相对于画布的比例(范围0-1)。
import matplotlib.pyplot as plt # 定义统一的Axes位置与尺寸(可根据标签长度调整) fixed_pos = [0.15, 0.15, 0.7, 0.7] # 第一个图表 fig1, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(3.5, 3)) ax1.plot([0.1, 0.2, 0.3]) ax1.set_ylabel('Y', weight='bold') ax1.set_xlabel('X', weight='bold') ax1.set_position(fixed_pos) # 第二个图表 fig2, ax2 = plt.subplots(nrows=1, ncols=1, figsize=(3.5, 3)) ax2.plot([1, 2, 3]) ax2.set_ylabel('Y', weight='bold') ax2.set_xlabel('X', weight='bold') ax2.set_position(fixed_pos) plt.show()
注意:如果坐标轴标签较长,需要调整
left或bottom的值,确保标签不会被画布边缘截断。
方法3:使用GridSpec精确控制布局
适合更复杂的布局场景,通过定义Axes的边界参数,确保不同图表的绘图区域完全一致。
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec # 第一个图表 fig1 = plt.figure(figsize=(3.5, 3)) gs1 = GridSpec(1, 1, left=0.15, right=0.85, bottom=0.15, top=0.85) ax1 = fig1.add_subplot(gs1[0]) ax1.plot([0.1, 0.2, 0.3]) ax1.set_ylabel('Y', weight='bold') ax1.set_xlabel('X', weight='bold') # 第二个图表 fig2 = plt.figure(figsize=(3.5, 3)) gs2 = GridSpec(1, 1, left=0.15, right=0.85, bottom=0.15, top=0.85) ax2 = fig2.add_subplot(gs2[0]) ax2.plot([1, 2, 3]) ax2.set_ylabel('Y', weight='bold') ax2.set_xlabel('X', weight='bold') plt.show()
这里right - left对应Axes的宽度比例,top - bottom对应高度比例,只要两个图表的参数完全一致,绘图区域的宽高就会完全相同。
内容的提问来源于stack exchange,提问作者Ruslan
相关产品推荐
相关产品推荐

