Skip to main content
 首页 » 编程设计

python之不显示绘图 : correct use of matplotlib. use()

2024年10月01日7mq0036

我需要在没有显示器的系统上绘图。 如果我天真地使用 matplotlib.pyplot.plt 绘图,我会得到

    raise RuntimeError('Invalid DISPLAY variable') 

我发现 matplotlib.use() 可以在这种情况下使用。 现在我有了一个主文件:

 **main.py:** 
 
 import my_module 
 .... 
 # do stuff 
 
 **my_module.py:** 
 
 import matplotlib 
 matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or     pylab! 
 import matplotlib.pyplot as plt     
 # do stuff 
 plt.plot(data) 

运行 main.py 时我得到:

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. 

但对我来说,我似乎是在导入 pyplot 之前调用它。后来我得到这个运行时错误

File "[OMIT]/python2.7/site-packages/matplotlib    /backends/backend_qt5.py", line 144, in _create_qApp 
raise RuntimeError('Invalid DISPLAY variable') 
RuntimeError: Invalid DISPLAY variable 

那么更改 matplotlib 后端的正确方法是什么?我不需要显示,但我需要能够使用 plt.savefig 存储图形

请您参考如下方法:

你需要

import matplotlib 
matplotlib.use('Agg') 

在新内核上,特别是如果您使用 ipython,在导入 matplotlib.pyplot 之前

我很好奇,也很高兴知道是否有办法清除/刷新 ipython 内核,而无需重新启动它;到目前为止,我的探索还没有成功。