ipympl icon indicating copy to clipboard operation
ipympl copied to clipboard

Excessive white space / margins with some plots.

Open asteppke opened this issue 10 months ago • 1 comments

With the current ipympl 0.9.6 (and probably earlier versions) I am observing excessive white space around axes in some cases when using the %matplotlib ipympl mode but not in the %matplotlib inline mode.

A small example to reproduce:

%matplotlib ipympl
from matplotlib import pyplot as plt

fig, ax = plt.subplots(figsize=(5, 3), constrained_layout=True)
ax.imshow([[1,2,3],[4,5,6],[7,8,9]])
ax.set_aspect(0.1)

This yields:

Image

And the same example in inline mode:

%matplotlib inline
from matplotlib import pyplot as plt

fig, ax = plt.subplots(figsize=(5, 3), constrained_layout=True)
ax.imshow([[1,2,3],[4,5,6],[7,8,9]])
ax.set_aspect(0.1)

Image

Especially larger figures then became unmanageable in the ipympl backend. Setting constrained_layout or using plt.tight_layout() does not seem to influence the margins. Can this behavior be influenced?

asteppke avatar Jan 16 '25 13:01 asteppke

inline ultimately sets bbox_inches='tight'and changes the figure shape which is why there is less whitespace. The tight or constrained layouts move axes around inside of the figure without changing the figize. With the aspect ratio you are using that is the least possible amount of whitespace without making the figure smaller.

This is not unique to ipympl. You can see the same behavior with the qt backend:

Image

The solution here is to change your figsize to better match the aspect ratio of your plot

%matplotlib ipympl
from matplotlib import pyplot as plt

fig, ax = plt.subplots(figsize=(5, 3), constrained_layout=True)
ax.imshow([[1,2,3],[4,5,6],[7,8,9]])
ax.set_aspect(0.1)
Image

plt.tight_layout() does not seem to influence the margins. Can this behavior be influenced?

Unfortunately I don't think there is a way to automatically change the figsize to better match the axes. What bbox_inches='tight' in savefig does is effectively to crop the figure before display, but that only makes sense when using a static display as in inline.

ianhi avatar Feb 18 '25 15:02 ianhi