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

2022-01-10 00:00:00 python matplotlib anaconda

问题描述

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

I'm studying matplotlib and don't know how to just save the graph and not print it on the screen.

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

  1. 只需使用 plt.close() ,这不会改变后端并且不会显示图形.

  1. 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

相关文章