Embedding a Jupyter Notebook on a Static Web Page

Posted on 11 November 2022 in posts

banner-jupyter-embed

Jupyter Notebook has been the leading software for interactive computing in Python and, more recently, many other coding languages. Its usefulness have made it more or less ubiquitous in data science and more generally in scientific research.

In this blog, I will often present code snippets in Jupyter Notebook, and I wanted to find out how to share them on static web pages. In this post I'll present you the solutions I found.

Embedding a notebook via GitHub Gist

The easiest way to display a Jupyter Notebook on your website or blog post is by using GitHub gist. Gist will host and display the notebook, while providing a script to embed the content in the page.

The steps to follow are:

  1. Create and run your jupyter notebook
  2. Save the output as a .ipynb
  3. Open it with a text editor and copy the content
  4. Create a new gist via https://gist.github.com/
  5. Give the Gist a name and save it as a public gist Drop down menu for creating gists. "Create public gist" is selected
  6. Copy the embed script from the top right menu Drop down menu for sharing gists. "Embed" option is selected
  7. Paste the script in your blog
  8. Profit!

The resulting notebook is perfect for display, but is not interactive. This method is still really useful to quickly present and share results.

Embedding a live notebook with JupyterLite

Recently, a JupyterLab distribution capable of running entirely in a web browser has been made available as unofficial release. Other than deploying it into your own web server, JupyterLite includes a minimal REPL application ready to use, that can be embedded on any website.

The live notebook can be easily included by adding this code in your page:

<iframe  
  src="https://jupyterlite.github.io/demo/repl/index.html?kernel=python">,
</iframe>

which will give you this result:

Additionally, you can specify the size of the iframe with the width and height keywords, as well as the colour theme with theme=JupyterLab Dark or theme=JupyterLab Light

Finally, you can have it automatically execute code on start up by passing &code= to the source URL.

You can break the code in multiple lines with %0A, and you can even add multiple cells by appending other instances of the code keyword.

For example:

<iframe
  src="https://jupyterlite.github.io/demo/repl/index.html?kernel=python&theme=JupyterLab Dark&code=
import numpy as np %0A
import matplotlib.pyplot as plt %0A
a = np.arange(15).reshape(3, 5) %0A
a&code=plt.imshow(a) %0A
plt.show()"
  width="100%"
  height="600px"
></iframe>

will result in this:

The resulting notebook is running live, and can accept user code to run interactively.

I hope you enjoyed this small tutorial. Thanks for reading.