We align the xlabels and ylabels using short calls to
and . We also show a manual way to align the ylabels
using the method of the yaxis object. Note this requires
knowing a good offset value which is hardcoded.
importmatplotlib.pyplotaspltimportnumpyasnpfig,axs=plt.subplots(2,3,figsize=(8.9,5.5),layout='constrained',gridspec_kw={'wspace':0.1})# add sample data and labelsforaxinaxs.flat:scale=2000ifax.get_subplotspec().is_first_row()else1ax.plot(scale*(1-np.exp(-np.linspace(0,5,100))))ifax.get_subplotspec().is_last_row():ax.set_xlabel('xlabel',bbox=dict(facecolor='yellow',pad=5,alpha=0.2))ax.set_ylabel('ylabel',bbox=dict(facecolor='yellow',pad=5,alpha=0.2))ax.set_ylim(0,scale)# Modify ticks to get different margins in some plotsaxs[0,0].xaxis.tick_top()axs[1,2].tick_params(axis='x',rotation=55)axs[0,0].set_title('ylabels not aligned')# Align labelsfig.align_titles()# Align titlesfig.align_xlabels()# Align all x-axis labelsfig.align_ylabels(axs[:,1])# Align only the second column's y-labelsaxs[0,1].set_title('fig.align_ylabels()')# Manually adjust y-labels for the third columnforaxinaxs[:,2]:ax.yaxis.set_label_coords(-0.3,0.5)axs[0,2].set_title('ylabels manually aligned')plt.show()