“import matplotlib.pyplot as plt” in virtualenv,如何解决?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (86)

我正在虚拟环境中使用Flask。我能够用pip安装matplotlib,而且我可以import matplotlib在Python会话中。但是,当我导入它时

matplotlib.pyplot as plt

我得到以下错误:

>>> import matplotlib.pyplot as plt

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "//anaconda/envs/myenv/lib/python2.7/site-packages/matplotlib/pyplot.py", line 109, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "//anaconda/envs/myenv/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "//anaconda/envs/myenv/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py", line 24, 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.

我不明白为什么它要求我安装Python作为框架。它不是已经存在了吗?

提问于
用户回答回答于

如果您已经在虚拟环境中使用pip安装了matplotlib,则只需键入以下内容:

$ cd ~/.matplotlib
$ nano matplotlibrc

用户回答回答于

下面是一个示例python片段,您可以尝试并测试matplotlib。

import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [0, 3, 7])
plt.show()

扫码关注云+社区