ChatGPT解决这个技术问题 Extra ChatGPT

Installation Issue with matplotlib Python [duplicate]

This question already has answers here: python matplotlib framework under macosx? (11 answers) Closed 8 years ago.

I have issue after installing the matplotlib package unable to import matplotlib.pyplot as plt. Any suggestion will be greatly appreciate.

>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "//anaconda/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg/matplotlib/pyplot.py", line 98, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "//anaconda/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg/matplotlib/backends/__init__.py", line 28, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "//anaconda/lib/python2.7/site-packages/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg/matplotlib/backends/backend_macosx.py", line 21, in <module>
    from matplotlib.backends import _macosx
**RuntimeError**: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends.
This link reports to the same issue you are presenting here.
Running pythonw instead of python worked for me

J
J4cK

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.

Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.


Yep, this works! If anyone wants to understand what happened, see matplotlib.org/faq/usage_faq.html#what-is-a-backend
Some users may not want to change the backend for all of their scripts. This page -- matplotlib.org/faq/usage_faq.html#what-is-a-backend -- tells another way: include the statement import matplotlib as mpl then mpl.use('TkAgg') right after that, then do the import for pyplot.
As a follow up question, why is there a folder .matplotlib in my root folder instead of in the virtual environment where I installed it?
Python 3.3.6, I get this: File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 40, in <module> import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named '_tkinter'
Thanks for this :D I used virtualenv with your fix and it worked for me!