Skip to content

Computing space needed for figure legend when using tight_layout #15257

Closed
@danijar

Description

@danijar

The use case it to place a figure legend below a grid of subplots, while also using tight_layout() to adjust the spacing between the subplots. This is possible using this code example, where LEGEND_HEIGHT must be set to the fraction of figure height used by the figure:

import collections
import matplotlib.pyplot as plt
import numpy as np

LEGEND_HEIGHT = 0.05

# Create figure with a grid of plots and random data.
fig, axes = plt.subplots(5, 5, figsize=(10, 8))
for ax in axes.flatten():
  ax.plot(np.cumsum(np.random.uniform(-1, 1, 100)), label='Line')

# Collect legend labels from all plots.
entries = collections.OrderedDict()
for ax in axes.flatten():
  for handle, label in zip(*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')

figure

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 tuning LEGEND_HEIGHT to a suitable value. Does Matplotlib allow for an automatic solution here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions