python - 如何在一个 django 模板页面中显示多个 matplotlib 图

标签 python django matplotlib

我正在使用 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

关于python - 如何在一个 django 模板页面中显示多个 matplotlib 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56428850/

相关文章:

python - 从主窗口中的 UI 文件加载具有信号槽定义的小部件

django - 为什么我收到 django Rest Framework swagger 的 "no module named urls"错误?

python - Matplotlib 报告字体系列 'serif' 未找到

python - [matplotlib] : understanding "set_ydata" method

python - 如何从浏览器访问在 Google Compute Engine 虚拟机上运行的 Django?

python - 如何判断图像是否暗?

python - Django OR 复杂查询

python - 在不破坏 Django Flow 的情况下修改模型

python - 有没有一个好的工具来聚合站点的 django 错误消息?

Python Jupyter 笔记本 : Put two histogram subplots side by side in one figure