ChatGPT解决这个技术问题 Extra ChatGPT

matplotlib Python的安装问题[重复]

这个问题在这里已经有了答案:python matplotlib framework under macosx? (11 个回答) 8 年前关闭。

安装 matplotlib 包后我遇到问题,无法将 matplotlib.pyplot 导入为 plt。任何建议将不胜感激。

>>> 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.
link 报告您在此处提出的同一问题。
运行 pythonw 而不是 python 对我有用

J
J4cK

问题原因

在 matplotlib 的 mac os 图像渲染后端(默认情况下使用 Cocoa 的 API 渲染的后端是什么)。有 Qt4Agg 和 GTKAgg 并且作为后端不是默认的。设置与其他windows或linux操作系统不同的macosx后端。

解决方案

我假设您已经安装了 pip matplotlib,在您的根目录中有一个名为 ~/.matplotlib 的目录。

在那里创建一个文件 ~/.matplotlib/matplotlibrc 并添加以下代码: backend: TkAgg

从此link,您可以尝试不同的图表。


是的,这行得通!如果有人想了解发生了什么,请参阅matplotlib.org/faq/usage_faq.html#what-is-a-backend
一些用户可能不想更改所有脚本的后端。这个页面 - matplotlib.org/faq/usage_faq.html#what-is-a-backend - 告诉另一种方式:包括语句 import matplotlib as mpl 然后 mpl.use('TkAgg') 紧随其后,然后为 pyplot 执行导入。
作为一个后续问题,为什么在我的根文件夹中而不是在我安装它的虚拟环境中有一个文件夹 .matplotlib?
Python 3.3.6,我明白了: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'
感谢这个:DI 在你的修复中使用了 virtualenv,它对我有用!