简体   繁体   English

如何在一个django模板页面中显示几个matplotlib图

[英]How to display several matplotlib plots in one django template page

I am working on a small app with Django framework. 我正在使用Django框架开发小型应用程序。 In one of my templates, I have a for loop in which I call an image of a matplotlib plot. 在我的一个模板中,我有一个for循环,在其中调用了matplotlib图的图像。 But Django is mixing all of my data : some plots charge well, others completly crash and some of them mix the data of two plots. 但是Django混合了我所有的数据:有些图充电良好,另一些则完全崩溃,其中有些混合了两个图的数据。 When I charge only one plot, it works fine but the problem occurs randomly when I have two or more plots on the same page. 当我只收取一个地块时,它可以正常工作,但是当我在同一页面上有两个或多个地块时,问题会随机发生。

I understand that the problem is due to the simultaneous creation of all plots. 我知道问题出在所有地块的同时创建。 Matplotlib is not designed for Django's multi-threading. Matplotlib不是为Django的多线程设计的。 So, I am looking for a way to create the plots in the right order. 因此,我正在寻找一种以正确的顺序创建图的方法。

Creation of the plot in views.py 在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

The for loop in the cluster 集群中的for循环

{% for key, h in dict.items %}
    <img src="{% url 'GraphsTS' h=h %}">
{% endif %}

I expect the plots to be created one after the other. 我希望这些地块可以一个接一个地创建。 It does not really matter if it slows down my application. 这是否会减慢我的应用程序的速度,并不重要。

I find a suitable solution by myself if anyone here is interested, I am using the RLock() function. 如果有人在这里,我会自己找到合适的解决方案,我正在使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM