如何在一个django模板页面中显示几个matplotlib图 [英] How to display several matplotlib plots in one django template page

查看:87
本文介绍了如何在一个django模板页面中显示几个matplotlib图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django框架开发一个小型应用程序.在我的一个模板中,我有一个for循环,在其中调用了matplotlib图的图像.但是Django混合了我所有的数据:有些地块收费良好,其他地块完全崩溃,其中一些地块混合了两个地块的数据.当我只收取一个地块时,它可以正常工作,但是当我在同一页面上有两个或多个地块时,问题会随机发生.

I am working on a small app with Django framework. In one of my templates, I have a for loop in which I call an image of a matplotlib plot. 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. 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.

我知道问题出在所有地块的同时创建.Matplotlib不是为Django的多线程设计的.因此,我正在寻找一种以正确的顺序创建图的方法.

I understand that the problem is due to the simultaneous creation of all plots. Matplotlib is not designed for Django's multi-threading. So, I am looking for a way to create the plots in the right order.

在views.py中创建情节

Creation of the plot in 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 %}

我希望这些图可以一个接一个地创建.这是否会减慢我的应用程序的速度,并不重要.

I expect the plots to be created one after the other. It does not really matter if it slows down my application.

推荐答案

如果有人对这里感兴趣,我会自己寻找合适的解决方案,我正在使用 RLock()函数.

I find a suitable solution by myself if anyone here is interested, I am using the RLock() function.

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

这篇关于如何在一个django模板页面中显示几个matplotlib图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆