简体   繁体   中英

No module named matplotlib with matplotlib installed Python 2.7

I am fairly new to python as well as matplotlib and I can't get it to work. From the code :

import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node("spam")
G.add_edge(1,2)
plt.show()

I get the error:

Traceback (most recent call last): 
    File "test.py2", line 2, in <module>
        import matplotlib.pyplot as plt 
ImportError: No module named matplotlib.pyplot

This occurs even though it seems to be installed in:

usr/lib/python2.7/dist-packages/matplotlib/

Do you guys have any ideas? Thanks in advance

You have 2 pythons installed on your machine, one is the standard python that comes with MacOSX and the second is the one you installed with ports (this is the one that has matplotlib installed in its library, the one that comes with macosx does not).

/usr/bin/python

Is the standard mac python and since it doesn't have matplotlib you should always start your script with the one installed with ports.

If python your_script.py works, then change the shebang ( #! ) to:

\#!/usr/bin/env python

Or put the full path to the python interpreter that has the matplotlib installed in its library.

thanks for your help. It appeared the wrong Python Version was used. By using

alias python=/usr/lib/python

it was fixed, but only temporarly.

To permanently set the alias correctly, I had to edit the ~/.bash_aliases and insert:

alias python=/usr/bin/python2.7

The other python version installed was 3.0 which was set as the defualt one, but without the matplotlib library.

You can check whether usr/lib/python2.7/dist-packages (if you are pretty sure matplotlib is installed here) is in your sys.path .

>>> import sys
>>> sys.path

If you don't find the path in the list, you can add lines below before importing matplotlib.

import sys
sys.path.insert(0, '/path/to/matplotlib')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM