Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython Notebook: How to combine HTML output and matplotlib figures?

The following code outputs rendered HTML in the result cell of an IPython command:

from IPython.core.display import HTML

def putHTML():
    source = """
    <h1>Yah, rendered HTML</h1>
    <h2>Here is an image</h2>
    <img src="http://lbkbd.in/wp-content/uploads/2014/10/HTML-Logo.png"/>
    """
    return HTML(source)

enter image description here

How can I use this approach to include figures generated by matplotlib on the fly in an HTML layout?

like image 799
clstaudt Avatar asked Mar 05 '15 12:03

clstaudt


People also ask

What does %% capture do in Jupyter?

IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.

How do you display plots in Jupyter notebook?

Usually, displaying plots involves using the show() function from PyPlot. With Jupyter notebooks, this isn't necessary as the plots are displayed after running the cells containing the code that generates them. These plots are by default, displayed inline, which means, they're displayed in the notebook itself.

What is the difference between %Matplotlib inline and %Matplotlib notebook?

%matplotlib notebook will lead to interactive plots embedded within the notebook. %matplotlib inline will lead to static images of your plot embedded in the notebook.


1 Answers

Since IPython already has a backend that generates HTML output for images, you can use their inline backend:

from matplotlib._pylab_helpers import Gcf
from IPython.core.pylabtools import print_figure 
from base64 import b64encode

# Plot something
plot([1,2],[3,4])

# Get a handle for the plot that was just generated
fig = Gcf.get_all_fig_managers()[-1].canvas.figure

# Generate a data URL for the image
# Matplotlib's display() would output the plot, so I do this manually.
# There might be a wrapper for this somewhere in IPython, if you're
# unhappy with this line..
image_data = "data:image/png;base64,%s" % b64encode(print_figure(fig)).decode("utf-8")

# Remove the plot from the list of plots for the current cell
Gcf.destroy_fig(fig)

# Now you can use the data URL in your HTML output
HTML("Foo Bar <br> <img src='%s'> <br> Baz" % image_data)
like image 134
Phillip Avatar answered Oct 27 '22 01:10

Phillip