[英]How to display several matplotlib plots in one django template page
我正在使用Django框架开发小型应用程序。 在我的一个模板中,我有一个for循环,在其中调用了matplotlib图的图像。 但是Django混合了我所有的数据:有些图充电良好,另一些则完全崩溃,其中有些混合了两个图的数据。 当我只收取一个地块时,它可以正常工作,但是当我在同一页面上有两个或多个地块时,问题会随机发生。
我知道问题出在所有地块的同时创建。 Matplotlib不是为Django的多线程设计的。 因此,我正在寻找一种以正确的顺序创建图的方法。
在views.py中创建图
def GraphsTS(request, h):
h = list(map(float, TS.split("-"))) # h is passed as text and transform to a list
f = plt.figure(figsize=(5,2))
plt.title('Title')
plt.xlabel('Date')
plt.ylabel('YLABEL')
plt.xticks(rotation='vertical')
bar1 = plt.plot(h, color='Green',alpha=0.65)
canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type='image/jpg')
canvas.print_jpg(response)
matplotlib.pyplot.close(f)
return response
集群中的for循环
{% for key, h in dict.items %}
<img src="{% url 'GraphsTS' h=h %}">
{% endif %}
我希望这些地块可以一个接一个地创建。 这是否会减慢我的应用程序的速度,并不重要。
如果有人在这里,我会自己找到合适的解决方案,我正在使用RLock()
函数。
from threading import RLock
verrou = RLock()
def GraphsTS(request, h):
with verrou:
h = list(map(float, TS.split("-"))) # h is passed as text and transform to a list
f = plt.figure(figsize=(5,2))
plt.title('Title')
plt.xlabel('Date')
plt.ylabel('YLABEL')
plt.xticks(rotation='vertical')
bar1 = plt.plot(h, color='Green',alpha=0.65)
canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type='image/jpg')
canvas.print_jpg(response)
matplotlib.pyplot.close(f)
return response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.