Content with notebooks

You can also create content with Jupyter Notebooks. The content for the current page is contained in a Jupyter Notebook in the notebooks/ folder of the repository. This means that we can include code blocks and their outputs, and export them to Jekyll markdown.

You can find the original notebook for this page at this address

Markdown + notebooks

As it is markdown, you can embed images, HTML, etc into your posts!

You an also \(add_{math}\) and

\[ math^{blocks} \]


\[\begin{split} \begin{align*} \mbox{mean} la_{tex} \\ \\ math blocks \end{align*} \end{split}\]

But make sure you $Escape $your $dollar signs $you want to keep!

Code blocks and image outputs

Jupyter Book will also embed your code blocks and output in your book. For example, here’s some sample Matplotlib code:

from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility

N = 10
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap =
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))

from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
                Line2D([0], [0], color=cmap(.5), lw=4),
                Line2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots(figsize=(10, 5))
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']);

Note that the image above is captured and displayed by Jekyll.

print("this works for code cells too, if you add a `margin` tag to them")
this works for code cells too, if you add a `margin` tag to them
# You can also include enriched outputs like Math
from IPython.display import Math
Math("\sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}")
\[\displaystyle \sum_{i=0}^n i^2 = rac{(n^2+n)(2n+1)}{6}\]

Removing content before publishing

You can also remove some content before publishing your book to the web. For example, in the original notebook there used to be a cell below…

You can also remove only the code so that images and other output still show up.

Below we’ll only display an image. It was generated with Python code in a cell, which you can see in the original notebook

thisvariable = "this plot *will* show up in the textbook."

fig, ax = plt.subplots()
x = np.random.randn(100)
y = np.random.randn(100)
ax.scatter(x, y, s=np.abs(x*100), c=x,
ax.text(0, .5, thisvariable, fontsize=20, transform=ax.transAxes)

And here we’ll only display a Pandas DataFrame. Again, this was generated with Python code from this original notebook.

import pandas as pd
df = pd.DataFrame([['hi', 'there'], ['this', 'is'], ['a', 'DataFrame']], columns=['Word A', 'Word B'])
Word A Word B
0 hi there
1 this is
2 a DataFrame

You can even style Pandas DataFrames! See the Pandas Styling docs for more information.

import pandas as pd

df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
df.iloc[3, 3] = np.nan
df.iloc[0, 2] = np.nan

def color_negative_red(val):
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

def highlight_max(s):
    highlight the maximum in a Series yellow.
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]\
    set_table_attributes('style="font-size: 10px"')
  A B C D E
0 1.000000 1.329212 nan -0.316280 -0.990810
1 2.000000 -1.070816 -1.438713 0.564417 0.295722
2 3.000000 -1.626404 0.219565 0.678805 1.889273
3 4.000000 0.961538 0.104011 nan 0.850229
4 5.000000 1.453425 1.057737 0.165562 0.515018
5 6.000000 -1.336936 0.562861 1.392855 -0.063328
6 7.000000 0.121668 1.207603 -0.002040 1.627796
7 8.000000 0.354493 1.037528 -0.385684 0.519818
8 9.000000 1.686583 -1.325963 1.428984 -2.089354
9 10.000000 -0.129820 0.631523 -0.586538 0.290720

Testing popouts before headers

Interactive outputs

We can even do the same for interactive material. Below we’ll display a map using folium. When the notebook is converted to Markdown, the code for creating the interactive map is retained.

Note that this will only work for some packages. They need to be able to output standalone HTML/Javascript, and not depend on an underlying Python kernel to work.

import folium
m = folium.Map(
    location=[45.372, -121.6972],
    tiles='Stamen Terrain'

    location=[45.3288, -121.6625],
    popup='Mt. Hood Meadows',

    location=[45.3311, -121.7113],
    popup='Timberline Lodge',

    location=[45.3300, -121.6823],
    popup='Some Other Location',
    icon=folium.Icon(color='red', icon='info-sign')

Make this Notebook Trusted to load map: File -> Trust Notebook

Rich outputs from notebook cells

Because notebooks have rich text outputs, you can store these in your Jupyter Book as well!

# The ! causes this to run as a shell command
!jupyter -h
usage: jupyter [-h] [--version] [--config-dir] [--data-dir] [--runtime-dir]
               [--paths] [--json] [--debug]

Jupyter: Interactive Computing

positional arguments:
  subcommand     the subcommand to launch

optional arguments:
  -h, --help     show this help message and exit
  --version      show the jupyter command's version and exit
  --config-dir   show Jupyter config dir
  --data-dir     show Jupyter data dir
  --runtime-dir  show Jupyter runtime dir
  --paths        show all Jupyter paths. Add --json for machine-readable
  --json         output paths as machine-readable json
  --debug        output debug information about paths

Available subcommands: bundlerextension kernel kernelspec migrate nbconvert
nbextension notebook run server serverextension troubleshoot trust