MacOs + Virtualenv + ipython notebook下使用matplotlib

0.错误

在MacOs + Virtualenv + ipython notebook下使用matplotlib的时候会出现如下错误

**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.

原因是matplotlib需要调用一些系统GUI的backend,如Qt5Agg,GTK3Agg,TkAgg等。所以matplotlib无法直接在虚拟环境中使用。

1.解决办法

TkAgg的支持不需要底层支持,可以在ipython notebook中使用。因此只要把支持改成TkAgg即可。

修改matplotlib的backend,改成TkAgg

$ cd ~/.matplotlib
$ vim matplotlibrc
然后在文件里加入一行:backend: TkAgg

另一种方法是

import matplotlib as mpt
mpt.use('TkAgg')

参考:http://stackoverflow.com/questions/29433824/unable-to-import-matplotlib-pyplot-as-plt-in-virtualenv

2.在ipython notebook里面绘图

直接绘图会在弹出窗口里面绘图,在代码里加上

%matplotlib inline

3.最终

总的来说,按照如下方式import

import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
%matplotlib inline

4.不用notebook

现在还没有一种优雅的办法不用notebook在virtualenv中使用matplotlib,这是因为TkAgg以外的支持需要系统GUI支撑。而TkAgg无法在notebook以为使用。

方法有了!那就是python3,python3的virtualenv不存在这个问题。

python3创建virtualenv(与python2.7不同):

$ python -m venv .p3env
$ source .p3env/bin/activate
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值