Skip to content

[Bug]: Saving a NonUniformImage with bbox_inches="tight" raises TypeError when extent is omitted #32707

Backlog

Description

@LegalZhang

Bug summary

I can save an image on an unevenly spaced grid with fig.savefig("grid.png"). When I add bbox_inches="tight" to trim the margins, saving the same figure raises a TypeError.

Code for reproduction

import sys, io, numpy as np, matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
from matplotlib.image import NonUniformImage
print(matplotlib.__version__)
def fig_with_nui():
    fig, ax = plt.subplots()
    im = NonUniformImage(ax)
    im.set_data(np.array([0, 1, 4]), np.array([0, 1, 4]), np.arange(9.).reshape(3, 3))
    ax.add_image(im); ax.set(xlim=(0, 4), ylim=(0, 4))
    return fig
for name, act in [("plain", lambda f: f.savefig(io.BytesIO())),
                  ("tight bbox", lambda f: f.savefig(io.BytesIO(), bbox_inches="tight")),
                  ("tight_layout", lambda f: (f.tight_layout(), f.savefig(io.BytesIO()))),
                  ("constrained", lambda f: (f.set_layout_engine("constrained"), f.savefig(io.BytesIO())))]:
    try: act(fig_with_nui()); print(name, "ok")
    except Exception as e: print(name, type(e).__name__, e)

Actual outcome

3.11.2
plain ok
tight bbox TypeError cannot unpack non-iterable NoneType object
tight_layout TypeError cannot unpack non-iterable NoneType object
constrained TypeError cannot unpack non-iterable NoneType object
m12-plain

Expected outcome

Tight export should save the same grid with the margins trimmed, and both layout modes should draw it successfully. Passing the grid bounds explicitly as extent lets me save with bbox_inches="tight".

m12-tight-with-extent

Additional information

After set_data, im.get_extent() already returns (0, 4, 0, 4) for the grid in the script. The inherited AxesImage.get_window_extent() reads self._extent, which is still None. Calling fig.tight_layout() or saving with constrained layout hits the same error.

A comment on #8426 mentioned seeing this with NonUniformImage and gave a hist2d example. PR #9442 set the extent in pcolorfast. The example above constructs the image directly.

Operating system

macOS 26.6.2 (arm64)

Matplotlib Version

3.11.2 (release) and main at 20e8737

Matplotlib Backend

No response

Python version

3.12.16

Jupyter version

No response

Installation

git checkout

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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions