Yim*_*REN 2 python matplotlib anaconda
我正在研究matplotlib,不知道如何只保存图形而不将其打印在屏幕上。
因此,我已经在Internet上进行了一些研究,很多答案都说解决方案是matplotlib.use('Agg')。而且必须在导入matplotlib.pyplot或pylab之前。
然后,当我在脚本的第一行中添加它时,它根本无法工作。
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)
Run Code Online (Sandbox Code Playgroud)
我使用Anaconda Spyder,所以我重新启动了内核并再次运行我的脚本,我得到了同样的错误信息。
然后,我再次重新启动内核,并在控制台中直接键入以下代码:
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)
Run Code Online (Sandbox Code Playgroud)
另外,如果我在脚本末尾删除“ plt.show()”或添加“ plt.ioff()”,该图将始终显示在屏幕上。
感谢大家的回答。现在,我有两种解决方案:
只需使用plt.close(),就不会更改后端,并且该图也不会显示。
使用plt.switch_backend('Agg'),这会将后端切换为“ agg”,并且屏幕上不打印数字。
小智 5
您可以尝试切换后端。显然 Spyder 在你之前加载 matplotlib,并且use没有效果。这可能会有所帮助:
How to switch backends in matplotlib / Python
小智 5
原始问题的答案很简单。如果您不想在屏幕上显示图形,请不要使用。plt.show()
因此,您要做的只是:
import matplotlib.pylab as plt
plt.plot(x,y) #whatever the x, y data be
#plt.show() """Important: either comment this line or delete it"""
plt.savefig('path/where/you/want/to/save/filename.ext')
#'filename' is either a new file or an already existing one which will get overwritten at the time of execution. 'ext' can be any valid image format including jpg, png, pdf, etc.
Run Code Online (Sandbox Code Playgroud)