【问题标题】:How to pass matplotlib graph in django template?如何在 django 模板中传递 matplotlib 图?
【发布时间】:2020-05-21 14:27:34
【问题描述】:

我正在尝试在 Django 模板中传递 matplotlib 图。在使用分析功能的views.py 文件中,我创建了一个图表。然后我将此图传递给我的 Django 模板。但是除了[<matplotlib.lines.Line2D object at 0x000001E39AB94F98>] 之外,我的 Django 模板中没有显示任何内容。我该如何解决这个问题?

我的意见.py

from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate,logout
from diabetes.forms import UserSignupForm,UserLoginForm,MeasurementsForm
from diabetes.models import Measurements
import pandas as pd
import  matplotlib.pyplot as plt

def analyze(request):

    qs=Measurements.objects.all().values()
    data=pd.DataFrame(qs)

    img=plt.plot(data.loc[:,'created'],data.loc[:,'d_value'])

    return render(request,'diabetes/analyze.html',{'df':img})

【问题讨论】:

    标签: python django matplotlib


    【解决方案1】:

    重复 - 这个问题已回答 here

    基本上,您需要将图像保存为文件(例如 png)

    buffer = BytesIO()
    plt.savefig(buffer, format='png')
    buffer.seek(0)
    image_png = buffer.getvalue()
    buffer.close()
    
    graphic = base64.b64encode(image_png)
    graphic = graphic.decode('utf-8')
    
    return render(request, 'graphic.html',{'graphic':graphic})
    

    然后在您的模板中使用该图像:

    <img src="data:image/png;base64,{{ graphic|safe }}">
    

    【讨论】:

    • 我使用过这种方法,但这次模板中只出现了一个图像图标。
    • @imtinan 如果您检查呈现的 HTML,您会在图像标签中看到什么?
    • 这显示在 imag 标记中
    • 当您运行plt.savefig() 时,您能找到该图像在您的文件系统中的保存位置吗?
    • 运行文件后,我发现我的应用程序中没有保存图像。供您参考,我在应用程序中没有静态文件夹。
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2015-10-25
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多