python - 如何在 django 模板中传递 matplotlib 图形?

标签 python django matplotlib

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

我的观点.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})

最佳答案

重复 - 此问题已得到解答 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 }}">

关于python - 如何在 django 模板中传递 matplotlib 图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61936775/

相关文章:

python - Django 管理站点不显示 ManyToManyField 关系

django - Django、Nginx 和 Gunicorn 上的 SSL

python-3.x - 当我们使用 Django(现有项目)进行身份验证并使用 FastAPI(新功能)进行 API 时,如何识别并保存正确的 "user"?

python - 有没有办法在 matplotlib 中标记多个 3d 表面?

如果高度为零,matplotlib 不可见条

python - plt.savefig() : ValueError: All values in the dash list must be positive

python - Cygwin 是否存在 openblas-devel?

python - 一行 for 循环将元素添加到 Python 中的列表

python - 使用 strptime 将具有偏移量的时间戳转换为 datetime obj

python - 在 pandas 数据框中删除特定条件下的值