0

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')
0

2 Answers 2

3

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'>
Sign up to request clarification or add additional context in comments.

1 Comment

It said "failed to load local resource"
1

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 />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.