Jac*_*ian 16 python django matplotlib
我问这个问题,因为我无法解决一个问题Python/Django
(实际上在纯Python中,没问题)导致了这个问题RuntimeError: tcl_asyncdelete async handler deleted by the wrong thread
.这在某种程度上与我matplotlib
在Django中渲染绘图的方式有关.我这样做的方式是:
...
import matplotlib.pyplot as plt
...
fig = plt.figure()
...
plt.close()
Run Code Online (Sandbox Code Playgroud)
我极其简化了我的代码.但问题是 - 即使我只有一行代码:
fig = plt.figure()
Run Code Online (Sandbox Code Playgroud)
我看到这个RuntimeError正在发生.我希望我能解决这个问题,如果我知道在Python/Django中关闭/清理/破坏绘图的正确方法.
Ale*_*kov 34
默认情况下,matplotlib使用TK gui工具包,当你在不使用工具包的情况下渲染图像时(即文件或字符串),matplotlib仍会实例化一个不显示的窗口,从而导致各种问题.为了避免这种情况,您应该使用Agg后端.它可以这样激活 -
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅matplotlib文档 - http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
上面的(可接受的)答案是终端环境中的解决方案。如果在IDE中进行调试,您可能仍想使用' TkAgg
'来显示数据。为了防止出现此问题,请应用以下两个简单规则:
fig = plt.figure()
示例代码:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data[:,:,:3])
plt.show()
Run Code Online (Sandbox Code Playgroud)
在MacOS和PyCharm IDE下,这被证明是一个很好的中间解决方案。
归档时间: |
|
查看次数: |
10242 次 |
最近记录: |