34

I want to embed a figure generated by python matplotlib into a html file with other content. Is that possible?

What I have thought is saving figures as png file and then use <img> tag to refer to it.

Some code I was trying to use are like:

import matplotlib.pyplot as plt
fig = plt.figure()
#plot sth
plt.savefig('test.png')

html = 'Some html head' + '<img src=\'test.png\'>' + 'Some more html'

with open('test.html','w') as f:
    f.write(html)

However, this will generate two files instead of one and I don't have a server to host the png file. Is that possible to embed the figure in the html? How do I do it in python.

Thank you.

2
  • 2
    What about use a base64 image? stackoverflow.com/questions/8499633/… Commented Feb 10, 2018 at 6:22
  • Outlook IOS client does not show image which is base64 encoded in the html format email. Is there any workaround? Commented Apr 26, 2020 at 1:26

2 Answers 2

58

You can write the image into a temporary file and encode it with base64 and then embed the encoded base64 image into your html. Most modern browsers will correctly render the image.

A short example modified from your code will be:

import matplotlib.pyplot as plt
import base64
from io import BytesIO

fig = plt.figure()
#plot sth

tmpfile = BytesIO()
fig.savefig(tmpfile, format='png')
encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8')

html = 'Some html head' + '<img src=\'data:image/png;base64,{}\'>'.format(encoded) + 'Some more html'

with open('test.html','w') as f:
    f.write(html)
Sign up to request clarification or add additional context in comments.

5 Comments

This worked for me, but I found I had to do one additional step of decoding the encoded. "<img src='data:image/png;base64,{}'>".format(encoded.decode("utf-8"))
I solved my problem by using encoded = base64.b64encode(tmpfile.getvalue()).decode('utf8') <img src='data:image/png;base64,{{}}'>
Awesome answer! 🙏🙏🙏🤓😎
Where is the image data in this
How to Convert matrix data into image inside HTML or else how to embedded matrix data as image in HTML
4

You can convert the image using base64 encoding: https://docs.python.org/3/library/base64.html#base64.encodebytes

and then embed the encoded string in the html like so: How to display Base64 images in HTML?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.