Can't use matplotlib.use('Agg'), graphs always show on the screen
我正在学习matplotlib,不知道如何保存图表而不在屏幕上打印。
所以我在互联网上做了一些研究,很多答案说解决方案是matplotlib.use("agg")。必须在导入matplotlib.pyplot或pylab之前。
然后,当我将它添加到脚本的第一行时,它根本不起作用。
1 2 3 4 5 6 7 8 9 10 11 12 | 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,所以我重新启动了内核并再次运行了我的脚本,得到了同样的错误信息。
然后我重新启动内核,并直接在控制台中键入以下代码:
1 2 3 4 5 6 7 8 9 10 | 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()",图形将始终打印在屏幕上。
谢谢大家的回答。现在我有两个解决方案:
只需使用
使用
你最初问题的答案很简单。如果你不想在屏幕上显示图表,就不要使用
1 2 3 4 5 | 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. |
江户十一〔一〕号
您可以尝试切换后端。显然,Spyder在加载Matplotlib之前就已经加载了,而