Skip to main content
 首页 » 编程设计

python之如何在不改变绘图的情况下更改 matplotlib 中的图形 Canvas 大小

2025年05月04日24shanyou

我想在 matplotlib 中用面板标签(“A”、“B”、...)来注释我正在制作的图形面板。例如,我想用一个大的“A"在图的左上角,如下面的代码所示。如何更改图 Canvas 以使这个“A”可见?

f = plt.figure(figsize=(5,5)) 
plt.subplot(2, 2, 1) 
# this "A" is clipped in the plot 
plt.annotate("A", 
             xy = (-0.25, 1.1), 
             xytext = (-0.25, 1.1), 
             xycoords = 'axes fraction', 
             textcoords = 'axes fraction', 
             fontsize=30) 
plt.subplot(2, 2, 2) 
plt.subplot(2, 2, 3) 
plt.subplot(2, 2, 4) 
plt.tight_layout() 
plt.show() 

有没有办法在子图的左侧添加“填充”,以便在不更改 figsize 参数的情况下将它们推到图形的右侧?并且不重新调整地 block ? Canvas 中有足够的空间来容纳标签和子图。

请您参考如下方法:

添加plt.subplots_adjust():

f = plt.figure(figsize=(5,5)) 
plt.subplot(2, 2, 1) 
# this "A" is clipped in the plot 
plt.annotate("A", 
             xy = (-0.25, 1.1), 
             xytext = (-0.25, 1.1), 
             xycoords = 'axes fraction', 
             textcoords = 'axes fraction', 
             fontsize=30) 
plt.subplot(2, 2, 2) 
plt.subplot(2, 2, 3) 
plt.subplot(2, 2, 4) 
plt.tight_layout() 
plt.subplots_adjust(top=0.9) 
plt.show() 

请确保不要将 plt.tight_layout 放在 plt.subplots_adjust 之后,因为这会覆盖更改。

另见 this 关于调整子图的页面。

使用上述代码生成的图形如下所示: