Python中如何去除matplotlib子图的固定box宽高比约束?
matplotlib子图比例残留异常解决方案
问题根因
之前为子图设置aspect='equal'和adjustable='box'参数后,对应axes对象的纵横比属性已经被修改,即便删除配置代码,只要运行环境没有重启、旧的figure实例没有被销毁,残留配置就会一直生效,导致y轴显示长度强制和x轴保持1:1,和数值范围无关。
修复方法
只需在循环配置子图的代码中,显式重置每个子图的纵横比为自动模式即可,具体修改如下:
修改后完整代码
import matplotlib.pyplot as plt import numpy as np # 运行前关闭所有已有figure,避免旧配置残留 plt.close('all') fig3,((ax1, ax2,ax3,ax4), (ax5,ax6,ax7,ax8)) = plt.subplots(2,4) ax_list=[ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8] liste_couleur=['c','m','r','g','k','y','b','saddlebrown'] fig3.suptitle('uk versus Tk pour des valeurs de densité') for i in np.arange(0,8,1): # 显式重置纵横比为自动,覆盖之前残留的equal设置 ax_list[i].set_aspect('auto') # 可选:重置adjustable参数为默认的datalim ax_list[i].set_adjustable('datalim') ax_list[i].set_title('densitée='+str(np.round(p[i],0))) ax_list[i].set_xlabel('Tk') ax_list[i].set_ylabel('uk') ax_list[i].plot(Tk[i,:],uk[i,:],liste_couleur[i],'.',markersize=8,linestyle='None') plt.tight_layout() plt.savefig('question_2_fig3') plt.show()
其他可选方案
如果上述修改后问题依然存在,可以尝试以下操作:
- 重启Python运行内核,清空所有历史变量配置
- 显式指定figure的尺寸,避免子图继承默认尺寸属性:
plt.subplots(2,4, figsize=(16, 8))
内容的提问来源于stack exchange,提问作者Emeric
相关产品推荐
相关产品推荐

