Skip to content

[Bug]: AttributeError: module 'matplotlib' has no attribute 'pyplot' on Mac #25506

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
tesnikio opened this issue Mar 19, 2023 · 14 comments
Closed
Labels
status: downstream fix required status: needs clarification Issues that need more information to resolve.

Comments

@tesnikio
Copy link

Bug summary

I'm getting a weird error locally on my Mac in Jupyter Notebook while trying to plot the graph with matplotlib.
The error is: AttributeError: module 'matplotlib' has no attribute 'pyplot' even though everything is imported correctly and code works on Google Colab.

Code for reproduction

import librosa
import librosa.display
import matplotlib.pyplot as plt

def plot_mel_spectrogram(wav_file_path):
    y, sr = librosa.load(wav_file_path, sr=None)

    S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128)

    log_S = librosa.power_to_db(S, ref=np.max)

    plt.figure(figsize=(10, 4))
    librosa.display.specshow(log_S, sr=sr, x_axis='time', y_axis='mel', cmap='coolwarm')
    plt.title('Mel spectrogram')
    plt.colorbar(format='%+02.0f dB')
    plt.tight_layout()
    plt.show()

Actual outcome

File ~/envs/venv39/lib/python3.9/site-packages/matplotlib/_api/__init__.py:226, in caching_module_getattr.<locals>.__getattr__(name)
    224 if name in props:
    225     return props[name].__get__(instance)
--> 226 raise AttributeError(
    227     f"module {cls.__module__!r} has no attribute {name!r}")

AttributeError: module 'matplotlib' has no attribute 'axes'

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/envs/venv39/lib/python3.9/site-packages/matplotlib_inline/backend_inline.py:99, in show(close, block)
     96 # only call close('all') if any to close
     97 # close triggers gc.collect, which can be slow
     98 if close and Gcf.get_all_fig_managers():
---> 99     matplotlib.pyplot.close('all')

File ~/envs/venv39/lib/python3.9/site-packages/matplotlib/_api/__init__.py:226, in caching_module_getattr.<locals>.__getattr__(name)
    224 if name in props:
    225     return props[name].__get__(instance)
--> 226 raise AttributeError(
    227     f"module {cls.__module__!r} has no attribute {name!r}")

AttributeError: module 'matplotlib' has no attribute 'pyplot'

Expected outcome

Plotted graph of mel spectrogram.

Additional information

I tried to reinstall it and import it in different ways, but it didn't help.

Operating system

MacOS

Matplotlib Version

3.7.1

Matplotlib Backend

module://matplotlib_inline.backend_inline

Python version

3.9.16

Jupyter version

6.5.3

Installation

pip

@tacaswell
Copy link
Member

Can you simplify this to not use librosa?

I am also confused by the traceback because there are two AttributeErrors in there.

I am still suspicious that this is an installation issue.

@tesnikio
Copy link
Author

Yeah, I tried to use w/o librosa and got the same issue plotting a trivial graph.
Another weird thing, it only happens in Safari web browser Jupyter session, in Chrome everything runs fine without any issues, as well as in Google Colab.

@tacaswell tacaswell added the status: needs clarification Issues that need more information to resolve. label Mar 20, 2023
@tacaswell
Copy link
Member

There is no way that the browser should be able to affect anything about the Python run time. If it is working in one browser and not another I suspect that this is due to using different kernels (and venvs) in each of those.

Can you please start with on entirely fresh venv reproduce this? I think we would need to see both how you set up the env and the output of pip list.

@tesnikio
Copy link
Author

But that browser stuff, that's what exactly happened to me, weird.
I tried it with entirely fresh venv and the issue disappeared, maybe the problem was in a corrupted virtual environment, idk.

Anyways, thanks for the assistance, resolved.

@tuantje
Copy link

tuantje commented Mar 23, 2023

Hi,

I had the exact same problem on Windows (very similar code to yours as I am also plotting spectograms. I tried so many things. It wouldn't even work in a new fresh venv, and the problem seemed to only occur in Jupyter Notebook and not in Spyder for example.

I found out that it works if I do not import librosa.display. I think it messes up the import of matplotlib(.pyplot).

Just import librosa and use librosa.display.X in the code.

Hope this helps if it occurs in the future!

@tacaswell
Copy link
Member

@tuantje Can you please report this to librosa?

attn @bmcfee

@rohithnocoder
Copy link

rohithnocoder commented Apr 2, 2023

Hi, I had this exact problem. I solved it by importing matplotlib.pyplot before importing librosa and it's sub components. Pretty easy fix but why I wonder 🤔

matplotlib version 3.7.1

@erkara
Copy link

erkara commented Apr 7, 2023

Hi, I had this exact problem. I solved it by importing matplotlib.pyplot before importing librosa and it's sub components. Pretty easy fix but why I wonder thinking

matplotlib version 3.7.1

this worked for me as well.

@mattpitkin
Copy link

mattpitkin commented Apr 21, 2023

As far as I can tell, this seems to be caused by the lazy loading of matplotlib in librosa's display.py. If I manually change:

if TYPE_CHECKING:
    import matplotlib
    ...

to

if True:
    import matplotlib
    ...

i.e., explicitly do the imports directly rather than with the lazy loader, then this problem doesn't seem to occur (for me at least).

Note: if I librosa v0.9.2, i.e., the version before the lazy loading was introduced, then it works without a problem.

@QuLogic
Copy link
Member

QuLogic commented Apr 21, 2023

This is a bug in matplotlib-inline: ipython/matplotlib-inline#24. If you check their imports, they import matplotlib and various other matplotlib.foo, but not matplotlib.pyplot, so when they use it, it's up to whatever happened before it whether it exists.

So explicitly importing matplotlib.pyplot first yourself will fix it. Or using %matplotlib notebook or %matplotlib widget (with ipympl installed) to select an interactive backend instead of the inline one should work as well.

@agucova
Copy link

agucova commented Jun 14, 2023

This is not an issue in matplotlib-inline, but rather in librosa, caused by their lazy loading. See here.

@stefanv
Copy link
Contributor

stefanv commented Jun 15, 2023

It is true that the problem is triggered by the lazy loading mechanism, but the more pertinent question here is whether the fancy footwork in the matplotlib init is truly needed. If it is, then we should investigate more carefully whether there is anything we can do in lazy_loader to help address the problem. It looks like matplotlib's __getattr__ machinery gets invoked when asking for a matplotlib submodule, at which point it gives up. The submodule is resolved before this point in the traditional import machinery.

@tacaswell
Copy link
Member

It looks like matplotlib's getattr machinery gets invoked when asking for a matplotlib submodule, at which point it gives up. The submodule is resolved before this point in the traditional import machinery.

I'm not sure if "traditional import machinery" is contrasting with mpl'- __getattr__,or lazy_loader

@bmcfee
Copy link
Contributor

bmcfee commented Jun 15, 2023

FWIW, I've patched this particular issue from the librosa side after realizing that we didn't actually need to directly lazy-load mpl submodules. (I don't think it's "wrong" to do so, but since we don't need to, I've reworked it.) This will roll out in the next release (some time this summer), but has already merged to main: librosa/librosa#1722

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: downstream fix required status: needs clarification Issues that need more information to resolve.
Projects
None yet
Development

No branches or pull requests

10 participants