无法使用matplotlib.use('Agg'),图形始终显示在屏幕上 [英] Can't use matplotlib.use('Agg'), graphs always show on the screen
问题描述
我正在研究matplotlib,不知道如何只保存图形而不将其打印在屏幕上.
I'm studying matplotlib and don't know how to just save the graph and not print it on the screen.
因此,我已经在Internet上进行了一些研究,许多答案都说解决方案是matplotlib.use('Agg').而且必须在导入matplotlib.pyplot或pylab之前.
So I've done some research on the Internet, many answers said the solution is matplotlib.use('Agg'). And it must be before importing matplotlib.pyplot or pylab.
然后,当我将其添加到脚本的第一行时,它根本无法工作.
Then when I added it in the first line of my script, it doesn't work at all.
import matplotlib
matplotlib.use('Agg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning: 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.
warnings.warn(_use_error_msg)
我使用Anaconda Spyder,所以我重新启动内核并再次运行我的脚本,我得到了同样的错误信息.
I use Anaconda Spyder, so I restarted kernel and ran my script again, I got same wrong information.
然后,我再次重新启动内核,并在控制台中直接键入以下代码:
Then I restarted kernel again and directly typed the following code in the console:
In[1]: import matplotlib as mpl
In[2]: mpl.use('Agg')
E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning: 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.
warnings.warn(_use_error_msg)
此外,如果我在脚本末尾删除'plt.show()'或添加'plt.ioff()',该图将始终显示在屏幕上.
Also, if I delete 'plt.show()' at the end of script or add 'plt.ioff()', the graph will always print on the screen.
感谢大家的回答.现在,我有两种解决方案:
Thanks for everyone's answer. Now I have two solutions:
-
只需使用
plt.close()
,就不会更改后端,并且图形也不会显示.
just use
plt.close()
, this will not change the backend and the figure doesn't show up.
使用plt.switch_backend('Agg')
,这会将后端切换为"agg",并且屏幕上不打印任何数字.
use plt.switch_backend('Agg')
, this will switch the backend to 'agg' and no figure printed on the screen.
推荐答案
您可以尝试切换后端.显然,Spyder会先加载matplotlib,而use
无效.这可能会有所帮助:
如何在matplotlib/Python中切换后端
You can try to switch the backend. Apparently Spyder loads matplotlib before you do, and use
has no effect. This may be helpful:
How to switch backends in matplotlib / Python
这篇关于无法使用matplotlib.use('Agg'),图形始终显示在屏幕上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!