Shivani Jaiswal
Shivani Jaiswal

Reputation: 11

Embed matplotlib bar graph in html page

I am trying to embed a matplotlib bar graph in html page. I have tried almost everything. here's my code-

views.py-

def result(request)
    plt.bar(x,h)
    plt.xlabel("Personality")
    plt.ylabel("course")
    plt.show()
return render(request,'result.html')

Upvotes: 0

Views: 1502

Answers (2)

Shivani Jaiswal
Shivani Jaiswal

Reputation: 11

I got the image in html page. Code-

views.py
import matplotlib.pyplot as plt
from io import BytesIO
import base64
def result(request):
            plt.bar(x,h)
            plt.xlabel("Personality")
            plt.ylabel("Scale")
            axes = plt. gca()
            axes. xaxis. label. set_size(15)
            axes. yaxis. label. set_size(15)
            buf = BytesIO()
            plt.savefig(buf, format='png', dpi=300)
            image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
            buf.close()
            return render(request,'result.html',{"image_base64":image_base64})

result.html-
<img src="data:image/png;base64,{{image_base64}}" alt="some text to display to your users when the image does not show correctly" width=500 height=auto />

Upvotes: 1

mrunali golait
mrunali golait

Reputation: 111

You using plt.show() which used to display figure. If you want to show this on HTML you can save the image by using plt.savefig('my_plot.png') and get the image path on the template.

   def result(request)
        plt.bar(x,h)
        plt.xlabel("Personality")
        plt.ylabel("course")
        plt.savefig('my_plot.png')
    
        return render(request,'result.html')

result.html

<img src='my_plot.png'>

Upvotes: 3

Related Questions