Jupyter Notebooks in WordPress

I’ve tried a few different ways of displaying Jupyter notebooks in a WordPress post. Here they are (written more as notes to myself than a comprehensive, step-by-step guide):

One option is to save the notebook to HTML inside Jupyter, upload it in WordPress (as a media item), and display that page as an iframe using a WP plugin.

Another is to upload to Gist and use their embed script (which seems to work fine when copy/pasted).

Both the above options suffer from excessive horizontal padding which limits display space, in my experience.

A third option is to copy/paste sections and use a syntax-highlighting WP extension to make the code look nice, but this is tedious (and I haven’t found a highlighter that I think looks great).

The nicest-looking option, I think, though the most technically-involved, is to save the notebook as HTML in Jupyter (i.e., File > Download as > HTML), copy the body of the page (save for the outer few <div> tags), and paste it into a WP post. I copied some CSS from this page into the WP “Additional CSS” (with a fix for the .c1 class, which was missing a period in the CSS declaration), which makes the Jupyter HTML render correctly. This is super-hacky, but I haven’t noticed it affecting any WP elements. I tweaked the CSS to keep the In [1] labels from showing, so that the code boxes can be wider:

.input_prompt {
	display: none;
}

By default, the output areas are limited to 300px of height and scroll after that. To display an area in full height, delete the output_stdout class from the surrounding div.

Since Jupyter embeds images as data inside the HTML file, plots come along for the ride automatically (though the text you copy/paste is really long as a result—you can upload the images and update those <img> tags if you want).

The end result looks like this:

In [13]:
dist, _, flow = cv2.EMD(sig1, sig2, cv2.DIST_L2)

print(dist)
print(_)
print(flow)
0.8333333134651184
None
[[0. 1. 1. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 2. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 2. 0.]]

(Footnote: the post I linked above links to a WP plugin that provides another possibility for embedding notebooks, but just using Gist’s embed script accomplishes the same thing in a similar way—I think that plugin is useful if you don’t want to lock in to Gist hosting.)

2 thoughts on “Jupyter Notebooks in WordPress”

    1. If WordPress.com provides the “Additional CSS” screen when customizing your theme, that last approach I described should work, though I haven’t tried myself.

Leave a Reply

Your email address will not be published. Required fields are marked *