Проблема с графикой pyplot из того же представления в django - PullRequest
0 голосов
/ 19 марта 2020

Я использую представление для создания графика с помощью matplotlib. Это представление выглядит следующим образом и зависит от аргумента id_projet.

def Graphique_view(request,id_projet):
    """
    s'occupe de l'affichage du graphique d'un projet
    """     
    projet = Projet.objects.get(pk=id_projet)
    date_debut = projet.date_debut
    semaine_fin = delta_semaine(date_debut,projet.date_fin)
    f= plt.figure(figsize=(16,9))
    plt.title('graphique')
    x1=[]
    y1=[]
    semaine = 0
    ETP = 0
    while semaine <= semaine_fin :
        compteur = 0
        for bilan in Bilan_horaire.objects.filter(projet=projet):
            if delta_semaine(date_debut,bilan.date) == semaine :
                ETP += bilan.ETP
                compteur +=1
                bilan_semaine=bilan
        if compteur != 0 :
            x1.append(bilan_semaine.date)
            y1.append(ETP)
        semaine+=1
    plt.plot(x1,y1,label = 'ETP travaillés')
    ETP = 0
    for livrable in projet.livrables :
        semaine = delta_semaine(date_debut,livrable.dernier_jalon.date_jalon)
        for utilisateur in projet.utilisateurs:
            ETP +=  ETP_ressources_livrable.objects.filter(utilisateur=utilisateur).filter(livrable=livrable).order_by('date_modification').reverse()[0].ETP_estime

        x=[date_debut,livrable.dernier_jalon.date_jalon,livrable.dernier_jalon.date_jalon]
        y=[ETP,ETP,0]
        plt.plot(x,y,label=livrable.libelle)

    myFmt = mdates.DateFormatter('S%W - %Y')
    axes = plt.gca()
    axes.xaxis.set_major_locator(mdates.DayLocator(interval=7)) 
    axes.xaxis.set_major_formatter(myFmt)
    plt.xticks(rotation = '-50')
    plt.xlabel('temps (semaines)')
    plt.ylabel('heures (ETP)')
    plt.legend()

    canvas = FigureCanvasAgg(f)    
    response = HttpResponse(content_type='image/jpg')
    canvas.print_jpg(response)
    matplotlib.pyplot.close(f)   
    return response

Ассоциированный URL-адрес: projet/<int:id_projet>/graphique

Это результат для projet/9/graphique, например projet 9 graph

И это результат для projet/10/graphique, например projet 10 graph

Теперь, если попытаться отобразить эти 2 изображения в html вот так:

<img src="{% url 'graphique_projet' 9 %}" />
<img src="{% url 'graphique_projet' 10 %}" />

У меня есть то, что я не хочу.

2 plots : one with a mix of the previous plots and one with nothing

Любая помощь будет признательна. Заранее спасибо!

1 Ответ

0 голосов
/ 20 марта 2020

Моя проблема была такой же, как та, которую спросил Брайс: Как отобразить несколько графиков matplotlib на одной django странице шаблона

Таким образом, решение заключается в использовании RLock() function.

Вот мой взгляд сейчас:

from threading import RLock
verrou = RLock()

def Graphique_view(request,id_projet):
    """
    s'occupe de l'affichage du graphique d'un projet
    """
    with verrou :
        projet = Projet.objects.get(pk=id_projet)
        date_debut = projet.date_debut
        semaine_fin = delta_semaine(date_debut,projet.date_fin)
        f= plt.figure(figsize=(16,9))
        plt.title('graphique')
        x1=[]
        y1=[]
        semaine = 0
        ETP = 0
        while semaine <= semaine_fin :
            compteur = 0
            for bilan in Bilan_horaire.objects.filter(projet=projet):
                if delta_semaine(date_debut,bilan.date) == semaine :
                    ETP += bilan.ETP
                    compteur +=1
                    bilan_semaine=bilan
            if compteur != 0 :
                x1.append(bilan_semaine.date)
                y1.append(ETP)
            semaine+=1
        plt.plot(x1,y1,label = 'ETP travaillés')
        ETP = 0
        for livrable in projet.livrables :
            semaine = delta_semaine(date_debut,livrable.dernier_jalon.date_jalon)
            for utilisateur in projet.utilisateurs:
                ETP +=  ETP_ressources_livrable.objects.filter(utilisateur=utilisateur).filter(livrable=livrable).order_by('date_modification').reverse()[0].ETP_estime

            x=[date_debut,livrable.dernier_jalon.date_jalon,livrable.dernier_jalon.date_jalon]
            y=[ETP,ETP,0]
            plt.plot(x,y,label=livrable.libelle)

        myFmt = mdates.DateFormatter('S%W - %Y')
        axes = plt.gca()
        axes.xaxis.set_major_locator(mdates.DayLocator(interval=7)) 
        axes.xaxis.set_major_formatter(myFmt)
        plt.xticks(rotation = '-50')
        plt.xlabel('temps (semaines)')
        plt.ylabel('heures (ETP)')
        plt.legend()

        canvas = FigureCanvasAgg(f)    
        response = HttpResponse(content_type='image/jpg')
        canvas.print_jpg(response)

        matplotlib.pyplot.close(f)
        return response
...