簡體   English   中英

如何在一個django模板頁面中顯示幾個matplotlib圖

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM