Skip to content

[Bug]: Colorbar is displaced when saving as .pdf with bbox_inches='tight' and by using inset_axes #27143

@Hexanders

Description

@Hexanders

Bug summary

I use imshow() with colorbar and inset_axes to zoom into the image. After saving the pdf with savefigure() and bbox_inches='tight' the colorbar is shifted.
Very similar to bug #25176, which has already been fixed.

The problem only occurs when using the bbox_inches='tight' option in combination with inset_axes.

Code for reproduction

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.cbook as cbook
import matplotlib.cm as cm
from matplotlib.patches import PathPatch
from matplotlib.path import Path
np.random.seed(19680801)
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
               origin='lower', extent=[-3, 3, -3, 3],
               vmax=abs(Z).max(), vmin=-abs(Z).max())
cb = plt.colorbar(mappable=im)
plt.show()
axins = inset_axes(ax, width='20%', height='20%', loc='upper right')
Z2 = axins.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
               origin='lower', extent=[-3, 3, -3, 3],
               vmax=abs(Z).max(), vmin=-abs(Z).max())
x1, x2, y1, y2 = -1,0,0,1
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
rectpatch, connects = ax.indicate_inset_zoom(axins, edgecolor = 'k',alpha=1, lw = 1)
connects[0].set_visible(False)
connects[1].set_visible(True)
connects[2].set_visible(True)
connects[3].set_visible(False)

fig.savefig("temp.pdf",
                bbox_inches='tight',
                transparent=True,
                format="pdf")

Actual outcome

temp.pdf

Expected outcome

Somthing like this:

temp.pdf

but with tight layout

Additional information

Python version :
Matplotlib version:

Operating system

OS: Linux Fedora 37 (Workstation Edition)

Matplotlib Version

3.8.0

Matplotlib Backend

module://ipympl.backend_nbagg

Python version

3.11.5

Jupyter version

module://ipympl.backend_nbagg

Installation

pip

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