Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7.9k
Closed
Description
The use case it to place a figure legend below a grid of subplots, while also usingtight_layout()
to adjust the spacing between the subplots. This is possible using this code example, whereLEGEND_HEIGHT
must be set to the fraction of figure height used by the figure:
importcollectionsimportmatplotlib.pyplotaspltimportnumpyasnpLEGEND_HEIGHT=0.05# Create figure with a grid of plots and random data.fig,axes=plt.subplots(5,5,figsize=(10,8))foraxinaxes.flatten():ax.plot(np.cumsum(np.random.uniform(-1,1,100)),label='Line')# Collect legend labels from all plots.entries=collections.OrderedDict()foraxinaxes.flatten():forhandle,labelinzip(*ax.get_legend_handles_labels()):entries[label]=handle# Adjust spacing between plots and make space for legend.fig.tight_layout(rect=(0,LEGEND_HEIGHT,1,1),h_pad=0.5,w_pad=0.5)# Add legend below the grid of plots.legend=fig.legend(entries.values(),entries.keys(),loc='upper center',bbox_to_anchor=(0.5,LEGEND_HEIGHT))fig.savefig('figure.png')
However, the number of subplots in the grid entries and entries in the legend frequently changes for me. Right now, this requires a lot of time for manually tuningLEGEND_HEIGHT
to a suitable value. Does Matplotlib allow for an automatic solution here?
Metadata
Metadata
Assignees
Labels
No labels