Skip to content
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

An error in use of inset_axes of mpl_toolkits in Jupyter Notebook #7052

Closed
jinshisai opened this issue Sep 15, 2023 · 6 comments
Closed

An error in use of inset_axes of mpl_toolkits in Jupyter Notebook #7052

jinshisai opened this issue Sep 15, 2023 · 6 comments
Labels
bug status:Needs Info status:Needs Triage Applied to issues that need triage

Comments

@jinshisai
Copy link

Description

I had an issue that plots of a color bar with inset_axes of mpl_toolkits.axes_grid1.inset_locator failed in jupyter notebook, although it works if I simply run through a python script or in ipython. I faced the following error messages:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/.pyenv/versions/3.11.4/lib/python3.11/site-packages/IPython/core/formatters.py:340, in BaseFormatter.__call__(self, obj)
    338     pass
    339 else:
--> 340     return printer(obj)
    341 # Finally look for special method names
    342 method = get_real_method(obj, self.print_method)

File ~/.pyenv/versions/3.11.4/lib/python3.11/site-packages/IPython/core/pylabtools.py:152, in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
    149     from matplotlib.backend_bases import FigureCanvasBase
    150     FigureCanvasBase(fig)
--> 152 fig.canvas.print_figure(bytes_io, **kw)
    153 data = bytes_io.getvalue()
    154 if fmt == 'svg':

File ~/.pyenv/versions/3.11.4/lib/python3.11/site-packages/matplotlib/backend_bases.py:2353, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
   2350         bbox_inches = bbox_inches.padded(pad_inches)
   2352     # call adjust_bbox to save only the given area
-> 2353     restore_bbox = _tight_bbox.adjust_bbox(
   2354         self.figure, bbox_inches, self.figure.canvas.fixed_dpi)
   2356     _bbox_inches_restore = (bbox_inches, restore_bbox)
   2357 else:

File ~/.pyenv/versions/3.11.4/lib/python3.11/site-packages/matplotlib/_tight_bbox.py:28, in adjust_bbox(fig, bbox_inches, fixed_dpi)
     26 locator = ax.get_axes_locator()
     27 if locator is not None:
---> 28     ax.apply_aspect(locator(ax, None))
     29 locator_list.append(locator)
     30 current_pos = ax.get_position(original=False).frozen()

File ~/.pyenv/versions/3.11.4/lib/python3.11/site-packages/matplotlib/colorbar.py:156, in _ColorbarAxesLocator.__call__(self, ax, renderer)
    154 def __call__(self, ax, renderer):
    155     if self._orig_locator is not None:
--> 156         pos = self._orig_locator(ax, renderer)
    157     else:
    158         pos = ax.get_position(original=True)

File ~/.pyenv/versions/3.11.4/lib/python3.11/site-packages/mpl_toolkits/axes_grid1/inset_locator.py:73, in AnchoredLocatorBase.__call__(self, ax, renderer)
     71 def __call__(self, ax, renderer):
     72     self.axes = ax
---> 73     bbox = self.get_window_extent(renderer)
     74     px, py = self.get_offset(bbox.width, bbox.height, 0, 0, renderer)
     75     bbox_canvas = Bbox.from_bounds(px, py, bbox.width, bbox.height)

File ~/.pyenv/versions/3.11.4/lib/python3.11/site-packages/matplotlib/offsetbox.py:399, in OffsetBox.get_window_extent(self, renderer)
    396 def get_window_extent(self, renderer=None):
    397     # docstring inherited
    398     if renderer is None:
--> 399         renderer = self.figure._get_renderer()
    400     bbox = self.get_bbox(renderer)
    401     try:  # Some subclasses redefine get_offset to take no args.

AttributeError: 'NoneType' object has no attribute '_get_renderer'

Reproduce

The exact code I run for a test is here.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes


# simulate data
x = np.linspace(-1,1,32)
y = x.copy()
xx, yy = np.meshgrid(x, y)
dd = np.exp(- xx*xx - yy*yy)


# plot
# figure
fig = plt.figure()
ax = fig.add_subplot(111)
# color plot
im = ax.pcolor(xx, yy, dd, shading='auto')

cax = inset_axes(ax,
                 width = '3%',
                 height = '100%',
                 bbox_to_anchor = (1. + 0.03, 0., 1., 1.), 
                 loc = 'lower left', 
                 bbox_transform = ax.transAxes, 
                 borderpad = 0.
                )
#plt.colorbar(im)
plt.colorbar(im, cax=cax)
plt.show()

Expected behavior

A plot like this was expected and it indeed appeared when the script was run by python or in ipython.

Screenshot 2023-09-15 at 23 52 17

Context

  • Operating System and version: Mac OS Ventura 13.5.1; M1 chip
  • Browser and version: Chrome Version 116.0.5845.140
  • Jupyter Notebook version: 7.0.2

The version of matplotlib was 3.7.2.

Troubleshoot Output
sys.version:
	3.11.4 (main, Aug 10 2023, 18:19:19) [Clang 14.0.3 (clang-1403.0.22.14.1)]

platform.platform():
macOS-13.5.1-arm64-arm-64bit

pip list:
Package Version
------------------------- -----------
anyio 3.7.1
appnope 0.1.3
argon2-cffi 21.3.0
argon2-cffi-bindings 21.2.0
arrow 1.2.3
astropy 5.3.1
astropy-helpers 4.0.1
astroquery 0.4.6
asttokens 2.2.1
async-lru 2.0.4
attrs 23.1.0
Babel 2.12.1
backcall 0.2.0
beautifulsoup4 4.12.2
bettermoments 1.8.5
bleach 6.0.0
bs4 0.0.1
casa-formats-io 0.2.1
certifi 2023.7.22
cffi 1.15.1
charset-normalizer 3.2.0
click 8.1.7
cloudpickle 2.2.1
comm 0.1.4
contourpy 1.1.0
corner 2.2.2
cycler 0.11.0
dask 2023.9.1
debugpy 1.6.7.post1
decorator 5.1.1
defusedxml 0.7.1
dynesty 2.1.2
emcee 3.1.4
executing 1.2.0
fastjsonschema 2.18.0
fonttools 4.42.0
fqdn 1.5.1
fsspec 2023.9.0
html5lib 1.1
idna 3.4
imfits 2.0.1
importlib-metadata 6.8.0
iniconfig 2.0.0
ipykernel 6.25.1
ipython 8.14.0
ipython-genutils 0.2.0
ipywidgets 8.1.0
isoduration 20.11.0
jaraco.classes 3.3.0
jedi 0.19.0
Jinja2 3.1.2
joblib 1.3.2
json5 0.9.14
jsonpointer 2.4
jsonschema 4.19.0
jsonschema-specifications 2023.7.1
jupyter 1.0.0
jupyter_client 8.3.0
jupyter-console 6.6.3
jupyter_core 5.3.1
jupyter-events 0.7.0
jupyter-lsp 2.2.0
jupyter_server 2.7.0
jupyter_server_terminals 0.4.4
jupyterlab 4.0.4
jupyterlab-pygments 0.2.2
jupyterlab_server 2.24.0
jupyterlab-widgets 3.0.8
keyring 24.2.0
kiwisolver 1.4.4
locket 1.0.0
MarkupSafe 2.1.3
matplotlib 3.7.2
matplotlib-inline 0.1.6
mistune 3.0.1
more-itertools 10.1.0
nbclient 0.8.0
nbconvert 7.7.3
nbformat 5.9.2
nest-asyncio 1.5.7
notebook 7.0.2
notebook_shim 0.2.3
numpy 1.25.2
overrides 7.4.0
packaging 23.1
pandas 2.0.3
pandocfilters 1.5.0
parso 0.8.3
partd 1.4.0
pexpect 4.8.0
pickleshare 0.7.5
Pillow 10.0.0
pip 23.2.1
platformdirs 3.10.0
pluggy 1.2.0
prometheus-client 0.17.1
prompt-toolkit 3.0.39
psutil 5.9.5
ptyprocess 0.7.0
pure-eval 0.2.2
pycparser 2.21
pyerfa 2.0.0.3
Pygments 2.16.1
pyparsing 3.0.9
pyspeckit 1.0.1
pytest 7.4.0
python-dateutil 2.8.2
python-json-logger 2.0.7
pytz 2023.3
pyvo 1.4.2
PyYAML 6.0.1
pyzmq 25.1.1
qtconsole 5.4.3
QtPy 2.3.1
radio-beam 0.3.4
referencing 0.30.2
requests 2.31.0
rfc3339-validator 0.1.4
rfc3986-validator 0.1.1
rpds-py 0.9.2
scikit-learn 1.3.0
scipy 1.11.1
seaborn 0.12.2
Send2Trash 1.8.2
setuptools 68.2.2
six 1.16.0
sniffio 1.3.0
soupsieve 2.4.1
spectral-cube 0.6.2
stack-data 0.6.2
terminado 0.17.1
threadpoolctl 3.2.0
tinycss2 1.2.1
toolz 0.12.0
tornado 6.3.2
tqdm 4.66.0
traitlets 5.9.0
tzdata 2023.3
uri-template 1.3.0
urllib3 2.0.4
wcwidth 0.2.6
webcolors 1.13
webencodings 0.5.1
websocket-client 1.6.1
wheel 0.41.2
widgetsnbextension 4.0.8
zeus-mcmc 2.5.4
zipp 3.16.2

Command Line Output

Browser Output
Screenshot 2023-09-16 at 0 04 37
@jinshisai jinshisai added bug status:Needs Triage Applied to issues that need triage labels Sep 15, 2023
@JasonWeill
Copy link
Collaborator

@jinshisai Thank you for opening this! Are you using side-by-side rendering when you run the code above? Can you attach a screen shot of what your notebook looks like after you run this code cell?

@jinshisai
Copy link
Author

Hi Jason,
Here is a screen shot of my notebook window when I run the code:
Screenshot 2023-09-20 at 11 01 27
The bottom of the error messages are cut off in this screen shot, but they are the same as the ones I posted. I am not sure what is exactly side-by-side rendering to be honest, but the figure is supposed to appear below the cell.

@RRosio
Copy link
Collaborator

RRosio commented Sep 26, 2023

Hi @jinshisai, thank you for the additional information. As @krassowski suggested in the Triage meeting, if you could please open an issue in https://github.com/matplotlib/ipympl, this is where you might find more information about addressing this issue.

@jinshisai
Copy link
Author

Hi @RRosio, ok thanks. I opened an issue in https://github.com/matplotlib/ipympl. However, ipympl has not been installed when I faced the issue. Anyway, I will wait their response. Thank you for your help.

@rcomer
Copy link

rcomer commented Sep 27, 2023

Hi, I believe this one was a Matplotlib bug which is fixed in v3.7.3. You can reproduce in a regular script if you use plt.savefig(filename, bbox_inches="tight”). I understand the inline backend uses bbox_inches="tight” automatically.
matplotlib/matplotlib#26287

@jinshisai
Copy link
Author

jinshisai commented Sep 27, 2023

Hi @rcomer, thanks for letting me know that. I just saw your information here, and was able to solve the issue by using matplotlib v3.8.0. Thanks again for your assistance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug status:Needs Info status:Needs Triage Applied to issues that need triage
Projects
None yet
Development

No branches or pull requests

4 participants