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

Skip to content

[Bug]: Colorbar is displaced when saving as .eps with bbox_inches='tight' #25176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Thomassien opened this issue Feb 8, 2023 · 6 comments · Fixed by #25193
Closed

[Bug]: Colorbar is displaced when saving as .eps with bbox_inches='tight' #25176

Thomassien opened this issue Feb 8, 2023 · 6 comments · Fixed by #25193
Assignees
Milestone

Comments

@Thomassien
Copy link

Bug summary

I am plotting with imshow() and create a colorbar. When saving the figure as .eps with savefig() and option bbox_inches='tight', the colorbar (without the spines) is displaced.

Code for reproduction

import matplotlib.pyplot as plt

fig = plt.figure()
plt.imshow([[1, 1], [1, 1]])
plt.colorbar()
plt.savefig("test.eps", bbox_inches='tight')
plt.show()

Expected outcome

Colorbar should be placed inside the spines as when using plt.show(). Also, saving as .png instead of .eps works correctly.

Actual outcome

test

Additional information

The bug does not happen when using Matplotlib version 5.2.3.

Operating system

Windows 10

Matplotlib version

3.6.3

Matplotlib backend

module://backend_interagg

Python version

3.11.0

@Thomassien Thomassien changed the title Colorbar is displaced when saving as .eps with bbox_inches='tight' [Bug]: Colorbar is displaced when saving as .eps with bbox_inches='tight' Feb 8, 2023
@jklymak
Copy link
Member

jklymak commented Feb 9, 2023

Confirmed on master as well. Note this doesn't happen for PDF, so it's an eps-only bug.

This bisects to c712f35, #21395

@jklymak
Copy link
Member

jklymak commented Feb 9, 2023

@anntzer did you have time to look at what went wrong here?

@anntzer
Copy link
Contributor

anntzer commented Feb 10, 2023

Oops, good catch. The fix is

diff --git i/lib/matplotlib/backends/backend_ps.py w/lib/matplotlib/backends/backend_ps.py
index a716859143..86bf4f04b6 100644
--- i/lib/matplotlib/backends/backend_ps.py
+++ w/lib/matplotlib/backends/backend_ps.py
@@ -824,8 +824,8 @@ class FigureCanvasPS(FigureCanvasBase):

     def _print_ps(
             self, fmt, outfile, *,
-            metadata=None, papertype=None, orientation='portrait',
-            **kwargs):
+            metadata=None, orientation='portrait', papertype=None,
+            bbox_inches_restore=None, **kwargs):

         dpi = self.figure.dpi
         self.figure.dpi = 72  # Override the dpi kwarg
@@ -860,7 +860,8 @@ class FigureCanvasPS(FigureCanvasBase):
                    if mpl.rcParams['text.usetex'] else
                    self._print_figure)
         printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,
-                orientation=orientation, papertype=papertype, **kwargs)
+                orientation=orientation, papertype=papertype,
+                bbox_inches_restore=bbox_inches_restore, **kwargs)

     def _print_figure(
             self, fmt, outfile, *,

i.e. _print_ps needs to have an explicit bbox_inches_restore kwarg (due to the implementation of signature sniffing in _switch_canvas_and_get_print_method). I'll try to write up a PR in the coming days, but anyone should feel free to adopt the patch if they can get this in faster.

Note that this is actually a regression in 3.6.0 that has been around for the whole 3.6 release cycle, so I guess it's technically not release critical for 3.7, but perhaps still a good idea to fix asap.

@tacaswell tacaswell added this to the v3.7.0 milestone Feb 10, 2023
ksunden added a commit to ksunden/matplotlib that referenced this issue Feb 10, 2023
ksunden added a commit to ksunden/matplotlib that referenced this issue Feb 10, 2023
@Hexanders
Copy link

Hexanders commented Oct 19, 2023

I am experiencing the same problem using inset_axes and savefigure() as pdf with the option bbox_inches='tight'.

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")

temp.pdf

OS: Linux Fedora 37 (Workstation Edition)
Python version : 3.11.5
Matplotlib version: 3.8.0

@rcomer
Copy link
Member

rcomer commented Oct 19, 2023

@Hexanders I think your problem is slightly different as it only shows when you include the inset axes. Please open a new issue so that we can track it.

@Hexanders
Copy link

@rcomer thank you for your quiq response. I will do so immediately.

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

Successfully merging a pull request may close this issue.

6 participants