How to increase padding (whitespace) for subplots when saving as png?

132 Views Asked by At

I have created a 4x2 subplot and I want to save the individual plots as separate png files. I am able to do this with the following code, however the tightbbox format is too tight and it makes it tough to read the title and x,y labels. Is there a way to increase the padding (whitespace) around each individual plot when using this tightbbox layout?

nrow = combined.shape[0]
ncol = combined.shape[1]
shape_row = int((nrow + 1)/2 if (nrow % 2) != 0 else nrow/2)

fig, axes = plt.subplots(shape_row, 2, figsize=(20,45))
fig.subplots_adjust(hspace=0.5, wspace=0.4) 
plt.rcParams['savefig.facecolor'] = 'white' 

axes = axes.ravel()

for i in range(nrow):

    axes[i].bar(range(2), combined.iloc[i,:2].values, color='blue', label=label_1)
    axes[i].plot(range(2,ncol-1), combined.iloc[i,2:-1], 'o-', color='orange', markersize=10, label=label_2)

    axes[i].plot([-1, 7], [combined.iloc[i,-1]]*2, linestyle='--', color='red', label=label_3)
    axes[i].plot([ncol-1,ncol-1],[0, combined.iloc[i,-1]], '--', color='red')

    axes[i].set_title(combined.index[i], fontsize=26, fontweight='bold', pad=15) 
    axes[i].set_xlabel('')
    axes[i].set_ylabel("(in local currency '000s)", fontsize=18, labelpad=10)
    axes[i].set_xticks(range(ncol))
    axes[i].set_xticklabels(combined.columns, rotation=45)
    axes[i].tick_params(labelsize=18, pad=10)
    axes[i].set_xlim([-.7, nrow-.97])
    axes[i].margins(x=0, y=0.2)

    blue_bar= mpatches.Patch(color='blue', label='aaa')
    orange_line=mlines.Line2D(range(2,ncol-1), combined.iloc[i,2:-1], color='orange', linestyle='-', marker = 'o', markersize=10, label='bbb')
    red_line=mlines.Line2D([-1, 7], [combined.iloc[i,-1]]*2, color='red', linestyle='--', label='ccc')

    lgd = axes[i].legend(handles=[blue_bar, orange_line, red_line],
                             loc='upper right', bbox_to_anchor=(1,1), fontsize=18, shadow=True, borderpad=1) 

    bbox = axes[i].get_tightbbox(fig.canvas.get_renderer())
    fig.savefig("subplot{}.png".format(i),
          bbox_inches=bbox.transformed(fig.dpi_scale_trans.inverted()))
0

There are 0 best solutions below