gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:57 25 4
gpt4 key购买 nike

我需要在没有显示器的系统上绘图。如果我天真地使用 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 内核,而无需重新启动它;到目前为止,我的探索还没有成功。

关于python - 不显示绘图 : correct use of matplotlib. use(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46561893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com