无法在virtualenv中"将matplotlib.pyplot导入为plt"

Roh*_*hit 66 python macos matplotlib virtualenv flask

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

matplotlib.pyplot as plt
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

我很困惑为什么它要求我安装Python作为框架.它不存在吗?"将Python安装为框架"是什么意思,我该如何安装它?

小智 159

这个解决方案对我有用.如果您已在虚拟环境中使用pip安装了matplotlib,则只需键入以下内容:

$ cd ~/.matplotlib
$ nano matplotlibrc
Run Code Online (Sandbox Code Playgroud)

然后,写backend: TkAgg在那里.如果您需要更多信息,请转到解决方案链接.

  • 单行:`echo'后端:TkAgg">〜/ .matplotlib/matplotlibrc`或`echo'后端:Agg">〜/ .matplotlib/matplotlibrc` (39认同)

Jas*_*yne 30

我得到了同样的错误,并试着Jonathan回答:

您可以使用后端Agg来解决此问题

转到User/yourname/.matplotlib并打开/创建matplotlibrc并添加以下行backend : Agg,它应该适合您.

我运行程序,没有错误,但也没有情节,我试过backend: Qt4Agg,它打印出我没有安装PyQt4.

然后我尝试了另一个后端:backend: TkAgg它有效!

所以也许我们可以尝试差异后端,有些可能会工作或安装像PyQt4这样的重新获得的软件包.

这是一个示例python片段,您可以尝试并测试matplotlib.

import matplotlib

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

plt.plot([1, 2, 3], [0, 3, 7])
plt.show()
Run Code Online (Sandbox Code Playgroud)


use*_*097 15

当我使用pip安装matplotlib时,我遇到了类似的问题.默认情况下,它安装了最新版本1.5.0.但是,我有另一个使用Python 3.4和matplotlib 1.4.3的虚拟环境,当我导入matplotlib.pyplot时,这个环境运行正常.因此,我使用以下方法安装了早期版本的matplotlib:

cd path_to_virtual_environment    # assume directory is called env3
env3/bin/pip install matplotlib==1.4.3
Run Code Online (Sandbox Code Playgroud)

我知道这只是一种解决方法,但它对我来说是一个短期的解决方案.


Ped*_*rte 8

如果您不想设置.matplotib/matplotlibrc配置文件,可以通过'Agg'在导入之后matplotlib和导入之前在运行时设置后端来避免此问题matplotlib.pyplot:

In [1]: import matplotlib

In [2]: matplotlib.use('Agg')

In [3]: import matplotlib.pyplot as plt

In [4]: fig, ax = plt.subplots(1, 1)

In [5]: import numpy as np

In [6]: x = np.linspace(-1., 1.)

In [7]: y = np.sin(x)

In [8]: ax.plot(x, y)
Out[8]: [<matplotlib.lines.Line2D at 0x1057ecf10>]

In [9=]: fig.savefig('myplot.png')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述