Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imbed matplotlib figure into iPython HTML

I want to dynamically write and display HTML with a code cell in Jupyter Notebook. The objective is to generate the HTML to display table, div, img tags in some way I choose. I want to capture img data and place it where I want in this auto generated HTML.

So far I've figured out that I can do the following:

from IPython.core.display import HTML

HTML("<h1>Hello</h1>")

and get:

Hello

That's great. However, I want to be able to do this:

HTML("<h1>Hello</h1><hr/><img src='somestring'/>")

and get something similar to a Hello with a horizontal line and an image below it, where the image is the same one as below.

import pandas as pd
import numpy as np

np.random.seed(314)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['x', 'y'])

df.plot.scatter(0, 1)

enter image description here

The result should look like this:

enter image description here

Question

What do I replace 'something' with in order to implement this? And more to the point, how do I get it via python?

I would have imagined there was an attribute on a figure object that would hold an serialized version of the image but I can't find it.

like image 748
piRSquared Avatar asked May 02 '16 20:05

piRSquared


2 Answers

After some digging around. Credit to Dmitry B. for pointing me in the right direction.

Solution

from IPython.core.display import HTML
import binascii
from StringIO import StringIO
import matplotlib.pyplot as plt

# open IO object
sio = StringIO()

# generate random DataFrame
np.random.seed(314)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['x', 'y'])

# initialize figure and axis
fig, ax = plt.subplots(1, 1)

# plot DataFrame
ax.scatter(df.iloc[:, 0], df.iloc[:, 1]);

# print raw canvas data to IO object
fig.canvas.print_png(sio)

# convert raw binary data to base64
# I use this to embed in an img tag
img_data = binascii.b2a_base64(sio.getvalue())

# keep img tag outter html in its own variable
img_html = '<img src="data:image/png;base64,{}&#10;">'.format(img_data)

HTML("<h1>Hello</h1><hr/>"+img_html)

I end up with:

enter image description here

like image 198
piRSquared Avatar answered Oct 19 '22 13:10

piRSquared


from IPython.core.display import Image
import io

s = io.BytesIO()

# make your figure here

plt.savefig(s, format='png', bbox_inches="tight")
plt.close()

Image(s.getvalue())
like image 28
Alex Lenail Avatar answered Oct 19 '22 13:10

Alex Lenail