imtinan
imtinan

Reputation: 181

How to pass matplotlib graph in django template?

I am trying to pass a matplotlib graph in Django template. in views.py file using analyze function, I have created a graph. Then i have passed this graph to my Django template. But nothing shows up in my Django template except [<matplotlib.lines.Line2D object at 0x000001E39AB94F98>]. How can i fix this?

my views.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})

Upvotes: 2

Views: 2909

Answers (1)

Eric
Eric

Reputation: 837

Repeat - this question was answered here

Basically, you'll need to save your image as a file (e.g. 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})

and then use that image in your template:

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

Upvotes: 5

Related Questions