How to display several matplotlib plots in one django template page

北慕城南 提交于 2021-02-11 07:46:11

问题


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.

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.

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

The for loop in the cluster

{% 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.


回答1:


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


来源:https://stackoverflow.com/questions/56428850/how-to-display-several-matplotlib-plots-in-one-django-template-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!