Mac系统下Python-Matplotlib问题及解决方法汇总

目录

 

问题一:matplotlib绘图窗口总是在最后面

解决办法

问题二:终端下无法import matplotlib

解决方法

如何快速运行脚本


问题一:matplotlib绘图窗口总是在最后面

在Mac系统下使用python的同学肯定遇到过这个问题:用matplotlib绘图的时候,窗口总是在最后面。比如我用的vscode编辑代码的,成图窗口总是在vscode后面,需要将vscode窗口缩小一点才能看到绘图结果。这显然不是我们想要的!

解决办法

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

import matplotlib as mpl之后进阶着跟一句mpl.use('TkAgg')即可将绘图窗口调到最前面。但是这句代码必须紧跟mpl且不能放在plt之后,比如:

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

将会提示错误,而且窗口依然在最后面:

This call to matplotlib.use() has no effect because the backend has already
been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
The backend was *originally* set to 'MacOSX' by the following code:
  File "test_MonokaiPro.py", line 3, in <module>
    import matplotlib.pyplot as plt
  File "/Users/zguo/.pyenv/versions/anaconda3-5.0.1/lib/python3.6/site-packages/matplotlib/pyplot.py", line 69,in <module>
    from matplotlib.backends import pylab_setup
  File "/Users/zguo/.pyenv/versions/anaconda3-5.0.1/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 14, in <module>
    line for line in traceback.format_stack()

问题二:终端下无法import matplotlib

在终端使用python脚本绘图可能出现如下的错误提示

from matplotlib.backends import _macosx
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 otherbackends. 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.

解决方法

此问题的解决方法与问题一相同,也可以有第二种解决方法:在~/.matplotlib/matplotlibrc文件中添加backend: TkAgg


如何快速运行脚本

                                                                                 code runner

安装runner插件,然后设置你喜欢的快捷键,比如我喜欢用shift+enter,聪明的你一下就想到了,没错,这个就是jupyter-notebook的默认运行快捷键!

                                                   设置快捷键:双击一下然后键入你喜欢的快捷键

 

转自:https://www.jianshu.com/p/9632b0cb0b47

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值