axes.get_tightbbox doesn't include legends... · Issue #9130 · matplotlib/matplotlib · GitHub
Skip to content

axes.get_tightbbox doesn't include legends... #9130

Description

@jklymak

Bug report

The bbox returned by axes.get_tightbbox doesn't include legends that overspill the axis.

Bug summary

This is an easy fix, but wasn't sure if the behavior was desired:

Code for reproduction

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
h = ax.plot(range(10), label='boo')
print(ax.get_tightbbox(fig.canvas.get_renderer()))
hh = ax.legend(h, 'Boooo', loc='center left', bbox_to_anchor=(0.9, 0.5))
print(ax.get_tightbbox(fig.canvas.get_renderer()))
print(hh._legend_box.get_window_extent(renderer))

Actual outcome

Bbox(x0=61.40277777777777, y0=29.077777777777776, x1=579.5, y1=425.9)
Bbox(x0=61.40277777777777, y0=29.077777777777776, x1=579.5, y1=425.9)
Bbox(x0=540.288888888889, y0=212.48888888888885, x1=659.413888888889, y1=262.71111111111105)

Expected outcome

The second bbox could have x1=659.41 to include the legend.

solution

in axes/_bases.py we could change:

     for child in self.get_children():
            if isinstance(child, OffsetBox) and child.get_visible():
                bb.append(child.get_window_extent(renderer))
            elif isinstance(child, Legend) and child.get_visible():
                 bb.append(child._legend_box.get_window_extent(renderer))

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions