![](/img/trans.png)
[英]Matplotlib and :RuntimeError: main thread is not in main loop:
[英]RuntimeError: main thread is not in main loop using Matplotlib with Django
我正在创建一个 Matplotlib 图以显示在我的 Django 应用程序的 HTML 模板中。 我将这个图保存在我的静态文件下,然后将它发送到 HTML,然后加载一个带有保存的.png
的img
标签。 在获得对该图的引用后,我在我的views.py
执行此操作。
# Get analysis visualization chart
figure = analyser.visualize_tweets(emotions)
# Save figure in static folder as png
figure.savefig('static/analysis_figures/figure.png')
# Inject html with figure path
response['analysis_figure_path'] = 'analysis_figures/figure.png'
return render(request, 'landing_page/index.html', response)
我的 HTML 是这样的:
<img src={% static analysis_figure %} alt="">
但是,这会导致RuntimeError: main thread is not in main loop
在我的views.py
的函数被第二次调用时发生(如果它在一切正常views.py
调用)。 为了防止这个错误,我将 Matplotlib 图形保存到main()
以在主线程中运行,然后在我的原始函数中调用它。 这修复了错误,但会阻止我的 HTML 重新加载,因此每次用户提交查询时,新图形都会显示在前一个之上,而不会删除前一个。 关于任何问题的任何想法?
我认为这篇文章解释了该怎么做: How to clean images in Python / Django?
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
如此处所述: https : //matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
为防止新图形显示在前一个上,请使用: plt.close() / figure.close()
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.bar(x, y, tick_label = tick_label,
width = 0.8, color = ['red','yellow', 'green'])
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('My bar chart!')
plt.style.use('fivethirtyeight')
fig=plt.gcf()
plt.close()
`enter code here`# convert graph
buf=io.BytesIO()
fig.savefig(buf,format='png')
buf.seek(0)
string =base64.b64encode(buf.read())
uri=urllib.parse.quote(string)
context={'imgdata':uri}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.