不能使用 matplotlib.use('Agg'),图形总是显示在屏幕上

Posted

技术标签:

【中文标题】不能使用 matplotlib.use(\'Agg\'),图形总是显示在屏幕上【英文标题】:Can't use matplotlib.use('Agg'), graphs always show on the screen不能使用 matplotlib.use('Agg'),图形总是显示在屏幕上 【发布时间】:2017-10-20 13:27:33 【问题描述】:

我正在研究 matplotlib,不知道如何只保存图形而不将其打印在屏幕上。

所以我在网上做了一些研究,很多答案说解决方案是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)

我使用 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)

另外,如果我在脚本末尾删除“plt.show()”或添加“plt.ioff()”,图形将始终打印在屏幕上。


感谢大家的回答。现在我有两个解决方案:

    只用plt.close(),不会改变后端,而且不显示图形。

    使用plt.switch_backend('Agg'),这会将后端切换到“agg”,屏幕上不会打印任何图形。

【问题讨论】:

你试过只使用plt.savefig吗?无需尝试更改后端。 是的,我的第一次尝试只是使用 plt.savefig。脚本完成后,所有图表都会显示在屏幕上。 现身很好。 但人形是否被保存?如果这是您的问题:之后使用plt.close 将其关闭。 plt.close 有效!!! :) 谢谢 【参考方案1】:

您可以尝试切换后端。显然 Spyder 会先加载 matplotlib,而 use 没有任何效果。这可能会有所帮助: How to switch backends in matplotlib / Python

【讨论】:

matplotlib.get_backend() 显示 Spyder 使用后端:'module://ipykernel.pylab.backend_inline'。使用 plt.switch_backend('Agg') 后,后端现在是 'agg'【参考方案2】:

原始问题的答案很简单。 如果您不想在屏幕上显示图表,请不要使用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.

【讨论】:

【参考方案3】:

plt.plot(x,y) plt.savefig('path/figure_filename.jpg',dpi=300)

【讨论】:

你能解释一下吗? 解释是不是把简单的事情复杂化了?此外,使用 plt.close() 删除对象就是这样,下一个数字从零开始。

以上是关于不能使用 matplotlib.use('Agg'),图形总是显示在屏幕上的主要内容,如果未能解决你的问题,请参考以下文章

python怎么替换plt.show

Linux服务器没有GUI的情况下使用matplotlib绘图

python用matplotlib画图提示Fail to allocate bitmap

matplotlib 生成 eps 插入到 tex

Matplotlib植入PyQt5 + QT5的UI呈现

matplotlib报错_tkinter.TclError: no display name and no $DISPLAY environment variable