在mac环境下,使用Python调用matplotlib库时出现ImportError: 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. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.
这是因为matplotlibrc文件中没有内容,或者backend(后端)为macosx。
Agg支持文件写入,但不支持窗口显示(绘图),所以要改为其他GUI后端:TkAgg、Wx、QtAgg、Qt4Agg等
解决方法一:修改matplotlibrc文件(较麻烦,每次新建项目均需要修改)
在终端环境下:找到matplotlibrc文件,它的路径在该项目的虚拟环境下
virtualenvs/XXXX/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc
在终端中输入以下命令,编辑文件:
$ vim ~/.matplotlib/mpl-data/matplotlibrc
输入 backend: TkAgg
输入冒号:,然后输入wq(写入退出)
以上也是plt.show()不显示图的解决办法
解决方法二:使用命令(但不改变matplotlibrc配置文件中的内容)
在项目中的.py文件开头,添加以下代码:
import matplotlib
matplotlib.rcParams['backend'] = 'TkAgg'
扩展:import seaborn as sns也可能出现文章开头提示的类似错误。
解决方法:import seaborn as sns需写在以上两行代码之后。
如果觉得内容不错,记得点“好看”
领取专属 10元无门槛券
私享最新 技术干货