Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib embed figures in auto generated html [duplicate]

Tags:

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.

like image 462
user9341366 Avatar asked Feb 10 '18 06:02

user9341366


People also ask

Does matplotlib overwrite Savefig?

Matplotlib Savefig will NOT overwrite old files.

What happens if I dont use %Matplotlib inline?

In the current versions of the IPython notebook and jupyter notebook, it is not necessary to use the %matplotlib inline function. As, whether you call matplotlib. pyplot. show() function or not, the graph output will be displayed in any case.

What can I use instead of %Matplotlib inline?

show() . If you do not want to use inline plotting, just use %matplotlib instead of %matplotlib inline .

How do I save my matplotlib graph as HTML?

show() converts any Matplotlib plot to HTML and opens the figure in the web browser. mpld3. save_html(fig,'myfig. html') method saves figures to HTML files for archiving or uploading as an iframe to a website, etc.


2 Answers

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) 
like image 125
Haochen Wu Avatar answered Sep 29 '22 08:09

Haochen Wu


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?

like image 24
PaW Avatar answered Sep 29 '22 08:09

PaW