无法使用matplotlib.use('Agg'),图形始终显示在屏幕上


问题内容

我正在研究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)

我使用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()”,则该图将始终显示在屏幕上。


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

  1. 只需使用plt.close(),就不会更改后端,并且该图也不会显示。

  2. 使用plt.switch_backend('Agg'),这会将后端切换为“ agg”,并且屏幕上不打印数字。


问题答案:

您可以尝试切换后端。显然,Spyder会先加载matplotlib,并且use无效。这可能会有所帮助: 如何在matplotlib /
Python中切换后端