如何让Matplotlib 3D子图适配figsize以消除左右空白?
解决Matplotlib 3.5.2中3D子图无法适配figsize的问题
你遇到的是Matplotlib 3.5.x版本中3D子图布局的兼容性问题,以下几种方法可以让子图更好地适配设定的figsize:
方法1:优化tight_layout参数
替换原代码中的plt.tight_layout()为fig.tight_layout(pad=0),pad参数控制画布边缘的留白,设为0可以最大程度压缩空白区域:
import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(16, 9)) ax = fig.add_subplot(projection='3d', elev=-150, azim=110) fig.tight_layout(pad=0) plt.show()
方法2:强制设置3D子图比例
通过ax.set_box_aspect()定义子图的三维比例,再配合tight_layout优化布局,能让子图更合理地填充画布:
import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(16, 9)) ax = fig.add_subplot(projection='3d', elev=-150, azim=110) ax.set_box_aspect([1, 1, 0.8]) # 可根据需求调整三维轴的比例 fig.tight_layout(pad=0) plt.show()
方法3:手动调整子图位置
直接设置子图的位置占比,让它填满整个画布,但这种方式可能会截断坐标轴标签,需要额外调整标签显示:
import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(16, 9)) ax = fig.add_subplot(projection='3d', elev=-150, azim=110) ax.set_position([0, 0, 1, 1]) # 子图从(0,0)位置开始,占满整个画布的宽高 plt.show()
内容的提问来源于stack exchange,提问作者hannes
相关产品推荐
相关产品推荐

