Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Bug]: Setting bbox_inches to a Bbox in fig.savefig resizes colorbar #22625

Closed
@pittwolfe

Description

@pittwolfe

Bug summary

Setting bbox_inches in fig.savefig to a specified Bbox rather than "tight" resizes the colorbar relative to when bbox_inches is not set—the resulting colorbar is a lot larger than it should be.

Code for reproduction

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

x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)

X, Y = np.meshgrid(x,y)

fig, ax = plt.subplots(figsize=(4,4))

pc = ax.pcolormesh(x, y, np.sin(X)*np.sin(Y))
fig.colorbar(pc, ax=ax, aspect=40)

# Uncomment the first fig.savefig to get the correct output on the second call
# fig.savefig('nobbox_inches.png')
fig.savefig('bbox_inches.png', bbox_inches=mpl.transforms.Bbox([[0, 0], [4, 4]]))

Actual outcome

bbox_inches

Expected outcome

nobbox_inches

Additional information

Calling fig.savefig without bbox_inches set first and then calling it again with bbox_inches set produces expected outcome.
Calling plt.show() prior to savefig also works.

Operating system

MacOS 12.2.1 (Monterey)

Matplotlib Version

3.5.1

Matplotlib Backend

inline (for interactive), png for plot, also a problem with pdf

Python version

3.9.10

Jupyter version

Jupyter lab 3.2.9

Installation

conda

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions