在mac环境下,运行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文件,路径:该项目虚拟环境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需写在以上两行代码之后。