IPython Notebook: how to combine HTML output and matplotlib numbers?

The following code displays the HTML in the result cell of the 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 the numbers created by matplotlib on the fly in the HTML layout?

+7
python html matplotlib ipython ipython-notebook
source share
3 answers

Since IPython already has a backend that generates HTML output for images, you can use their built-in 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 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) 
+10
source share

Another option is to follow the advice of this blog: http://protips.maxmasnick.com/hide-code-when-sharing-ipython-notebooks

In particular:

  • Copy this code to the top (first cell) of your IPython laptop (copying the code and comments directly from the link above, all credits belong to the blogger):

import IPython.core.display as di

This line will hide the default code when the laptop is exported as HTML:

di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

A button will be added to this line to switch the visibility of code blocks for use with the export version of HTML:

di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)

  1. Run the top cell (with the code above). You should see the β€œSwitch Code” button right below it when it finishes executing.

  2. Press the button to enable / disable the code. The same switching behavior will appear in both .ipynb and converted .html.

0
source share

If you just want to combine html output and graphics, the magic %matplotlib inline command somewhere in the beginning should be enough.

When you load your laptop as html, all graphics will be correctly encoded and included in your single html file.

-2
source share

All Articles