5

我正在创建一个 Matplotlib 图以显示在我的 Django 应用程序的 HTML 模板中。我将此图发送到 HTML,方法是将其保存在我的静态文件下,然后img使用保存的.png. 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在 myviews.py中的函数被第二次调用时发生(如果在一切正常时调用它)。为了防止这个错误,我将 Matplotlib 图保存到main()as 在主线程中运行,然后在我的原始函数中调用它。这修复了错误,但阻止了我的 HTML 重新加载,因此每次用户提交查询时,新图形都会显示在前一个图形上,而不会删除前一个图形。关于任何问题的任何想法?

4

2 回答 2

9

我认为这篇文章解释了该怎么做: 如何在 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()

于 2018-11-22T15:54:38.790 回答
-1
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}
于 2020-11-03T06:25:56.360 回答