Skip to content

[Bug]: Saving a figure with bbox_inches="tight" fails after inset_axes #26468

Closed
@obriene1

Description

@obriene1

Bug summary

After using inset_axes in mpl 3.7.2, savefig fails if bbox_inches is set to "tight". This does not fail in 3.7.1.

Code for reproduction

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

# Test data
x = [i for i in range(10)]
y = [i for i in range(10)]
x_sub = [i for i in range(5)]
y_sub = [i for i in range(5)]

# Initial figure
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

# Insetted axis and plot
cax = inset_axes(ax, width="30%", height="30%", loc="lower right")
cax.plot(x_sub, y_sub)

# Saving -- error due to bbox_inches part
fig.savefig("test_out.png", format="png", bbox_inches="tight")

Actual outcome

AttributeError in line 16 (replaced paths to script and lib):

Traceback (most recent call last):
File "<path_to_script>/bug_test.py", line 16, in
fig.savefig("test_out.png", format="png", bbox_inches="tight")
File "<path_to_lib>/lib/python3.9/site-packages/matplotlib/figure.py", line 3378, in savefig
self.canvas.print_figure(fname, **kwargs)
File "<path_to_lib>/lib/python3.9/site-packages/matplotlib/backend_bases.py", line 2353, in print_figure
restore_bbox = _tight_bbox.adjust_bbox(
File "<path_to_lib>/lib/python3.9/site-packages/matplotlib/_tight_bbox.py", line 28, in adjust_bbox
ax.apply_aspect(locator(ax, None))
File "<path_to_lib>/lib/python3.9/site-packages/mpl_toolkits/axes_grid1/inset_locator.py", line 73, in call
bbox = self.get_window_extent(renderer)
File "<path_to_lib>/lib/python3.9/site-packages/matplotlib/offsetbox.py", line 399, in get_window_extent
renderer = self.figure._get_renderer()
AttributeError: 'NoneType' object has no attribute '_get_renderer'

Expected outcome

A straight line in the main plot with an insetted second line in the lower right corner.

test_out

Additional information

This worked in mpl 3.7.1 (see expected outcome).

This doesn't happen if the bbox_inches kwarg is removed.

Operating system

MacOS

Matplotlib Version

3.7.2

Matplotlib Backend

Installed osx event loop hook. MacOSX

Python version

3.9.6

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions