Matplotlib GridSpec绘图尺寸不符:指定尺寸未生效求助
解决Matplotlib GridSpec子图保存后尺寸与设定不符的问题
你的问题核心在于**bbox_inches='tight'参数会自动调整画布尺寸以适配内容**,直接覆盖了你通过figsize设定的原始画布尺寸,导致输出图的实际尺寸和预期不符。
解决方案
移除plt.savefig()中的bbox_inches='tight'参数即可——你已经通过fig.subplots_adjust(left=0, right=1, bottom=0, top=1)将子图边距设为0,完全填满了设定的画布,不需要该参数额外裁剪。
修改后的代码如下:
import matplotlib.pyplot as plt import numpy as np import seaborn as sns # set up the figure fig = plt.figure(figsize=(4.2055, 2.2752)) # number of columns in the Gridspec fwid = 22 # set up the grid grid = plt.GridSpec(1, fwid) # set up the number of columns allocated to each subplot h0 = int((fwid-1)/3) h1 = int(h0*2) ax = [ fig.add_subplot(grid[:h0]), fig.add_subplot(grid[h0:h1]), fig.add_subplot(grid[h1]), ] hm1 = np.random.randn(10,10) hm2 = np.random.randn(10,10) # plot the heatmaps sns.heatmap( hm1, ax=ax[0], vmin=0, vmax=1, cbar=False ) sns.heatmap( hm2, ax=ax[1], vmin=0, vmax=1, # put the colorbar in the 3rd subplot cbar_ax=ax[2] ) ax[0].set_xticks(np.arange(0.5,10)) ax[0].set_xticklabels(np.arange(0.5,10)) ax[0].set_yticks(np.arange(0.5,10)) ax[1].set_yticks([]) ax[1].set_xticks(np.arange(0.5, 10)) ax[1].set_xticklabels(np.arange(0.5,10)) fig.subplots_adjust(left=0, right=1, bottom=0, top=1) plt.savefig('example.png', facecolor='white', transparent=False, dpi=300)
补充说明
如果确实需要保留bbox_inches='tight'(比如存在超出画布的元素需要裁剪),可以配合pad_inches=0参数来减少额外填充:
plt.savefig('example.png', facecolor='white', transparent=False, bbox_inches='tight', pad_inches=0, dpi=300)
不过这种方式仍可能出现微小尺寸偏差,最稳妥的还是直接移除bbox_inches='tight',毕竟你已经通过subplots_adjust消除了所有边距,子图完全填充了预设的画布。
内容的提问来源于stack exchange,提问作者Elsayeda
相关产品推荐
相关产品推荐

