I'm using matplotlib to plot my data in a 4x2 grid of subplots. The matplotlib.pyplot.tight_layout
automatically fits the subplots, legend, and text labels into a figure that I can save as png. However, when the legend is extremely long, tight_layout
seems to add extra horizontal space to some subplots.
What is the most efficient way to avoid this extra space? The subplots_adjust
function looks promising, but there's a lot of trial-and-error to adjust everything and I'm hoping to find a quicker automated solution using tight_layout
. My MWE is:
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(-5,5,100)
x1 = np.sin(t)
x2 = np.cos(t)
x3 = np.sin(2*t)
x4 = np.cos(2*t)
x5 = 2*np.sin(t)
x6 = 2*np.cos(t)
x7 = np.sin(0.5*t)
x8 = np.cos(0.5*t)
fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(10, 7))
for r in range(4):
for c in range(2):
ax[r,c].plot(t,x1,label='preliminary 1')
ax[r,c].plot(t,x2,label='preliminary 2')
ax[r,c].plot(t,x3,label='trial 1, result 1')
ax[r,c].plot(t,x4,label='trial 1, result 2')
ax[r,c].plot(t,x5,label='trial 1, result 6')
ax[r,c].plot(t,x6,label='trial 4, result 1')
ax[r,c].plot(t,x7,label='trial 12, result 2')
ax[r,c].plot(t,x8,label='trial 15, result 2')
ax[0,1].legend(loc='best', bbox_to_anchor = (0.3, -1.1, 1.2, 2))
plt.tight_layout()
plt.savefig('myfig.png')
plt.show()
If you use the newer Constrained Layout rather than tight_layout
then you can easily add a figure legend at the top right.
Changes are:
Create the figure with constrained layout
fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(10, 7), layout='constrained')
Get hold of the legend handles and labels from a single axes
handles, labels = ax[0, 1].get_legend_handles_labels()
Use these handles and labels in a figure legend
fig.legend(handles, labels, loc='outside right upper')
Remove the calls to ax.legend
and tight_layout
.