Jupyter Notebook files#

You can create content with Jupyter notebooks. For example, the content for the current page is contained in this notebook file.

Jupyter Book supports all Markdown that is supported by Jupyter Notebook. This is mostly a flavour of Markdown called CommonMark Markdown with minor modifications. For more information about writing Jupyter-flavoured Markdown in Jupyter Book, see Markdown files.

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
plt.ion()
<contextlib.ExitStack at 0x7f588ef16dd0>
# Fixing random state for reproducibility
np.random.seed(19680801)

N = 10
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap = plt.cm.coolwarm
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']);
../_images/a7a52b22adf7fc94d44d4ae8c80684960d682f2a33981e38e32f12000c519272.png

Note that the image above is captured and displayed in your site.

[Text(0.5, 1.0, 'Smoother lines')]
../_images/f1fc84c6cfe9738d2732dafabbb0e8f6bfba96a2f941e8d1c131f47db883d4f1.png

Removing content before publishing#

You can also remove some content before publishing your book to the web. For reference, you can download the notebook content for this page.

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

Hide code cell source
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, cmap=plt.cm.coolwarm)
ax.text(0, .5, thisvariable, fontsize=20, transform=ax.transAxes)
ax.set_axis_off()
../_images/71039ee17dedf77e1f189876ef1958be5c7ecc885ff123f1a5c24285693b06a6.png

Which works well if you’d like to quickly display cell output without cluttering your content with code. This works for any cell output, like a Pandas DataFrame.

Hide code cell source
import pandas as pd
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

See Removing code cell content for more information about hiding and removing content.

Interactive outputs#

We can do the same for interactive material. Below we’ll display a map using folium. When your book is built, the code for creating the interactive map is retained.

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

folium.Marker(
    location=[45.3288, -121.6625],
    popup='Mt. Hood Meadows',
    icon=folium.Icon(icon='cloud')
).add_to(m)

folium.Marker(
    location=[45.3311, -121.7113],
    popup='Timberline Lodge',
    icon=folium.Icon(color='green')
).add_to(m)

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

m
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[7], line 2
      1 import folium
----> 2 m = folium.Map(
      3     location=[45.372, -121.6972],
      4     zoom_start=12,
      5     tiles='Stamen Terrain'
      6 )
      8 folium.Marker(
      9     location=[45.3288, -121.6625],
     10     popup='Mt. Hood Meadows',
     11     icon=folium.Icon(icon='cloud')
     12 ).add_to(m)
     14 folium.Marker(
     15     location=[45.3311, -121.7113],
     16     popup='Timberline Lodge',
     17     icon=folium.Icon(color='green')
     18 ).add_to(m)

File ~/checkouts/readthedocs.org/user_builds/jupyter-book/envs/stable/lib/python3.11/site-packages/folium/folium.py:302, in Map.__init__(self, location, width, height, left, top, position, tiles, attr, min_zoom, max_zoom, zoom_start, min_lat, max_lat, min_lon, max_lon, max_bounds, crs, control_scale, prefer_canvas, no_touch, disable_3d, png_enabled, zoom_control, **kwargs)
    300     self.add_child(tiles)
    301 elif tiles:
--> 302     tile_layer = TileLayer(
    303         tiles=tiles, attr=attr, min_zoom=min_zoom, max_zoom=max_zoom
    304     )
    305     self.add_child(tile_layer, name=tile_layer.tile_name)

File ~/checkouts/readthedocs.org/user_builds/jupyter-book/envs/stable/lib/python3.11/site-packages/folium/raster_layers.py:139, in TileLayer.__init__(self, tiles, min_zoom, max_zoom, max_native_zoom, attr, detect_retina, name, overlay, control, show, no_wrap, subdomains, tms, opacity, **kwargs)
    137 self.tiles = tiles
    138 if not attr:
--> 139     raise ValueError("Custom tiles must have an attribution.")
    141 self.options = parse_options(
    142     min_zoom=min_zoom,
    143     max_zoom=max_zoom,
   (...)
    151     **kwargs,
    152 )

ValueError: Custom tiles must have an attribution.

Rich outputs from notebook cells#

Because notebooks have rich text outputs, you can store these in your Jupyter Book as well! For example, here is the command line help menu, see how it is nicely formatted.

!jupyter-book build --help
Usage: jupyter-book build [OPTIONS] PATH_SOURCE

  Convert your book's or page's content to HTML or a PDF.

Options:
  --path-output TEXT              Path to the output artifacts
  --config TEXT                   Path to the YAML configuration file
                                  (default: PATH_SOURCE/_config.yml)
  --toc TEXT                      Path to the Table of Contents YAML file
                                  (default: PATH_SOURCE/_toc.yml)
  -W, --warningiserror            Error on warnings.
  -n, --nitpick                   Run in nit-picky mode, to generates warnings
                                  for all missing references.
  --keep-going                    With -W, do not stop the build on the first
                                  warning, instead error on build completion
  --all                           Re-build all pages. The default is to only
                                  re-build pages that are new/changed since
                                  the last run.
  --builder [html|dirhtml|singlehtml|pdfhtml|latex|pdflatex|linkcheck|custom]
                                  Which builder to use.
  --custom-builder TEXT           Specify alternative builder provided by
                                  Sphinx, including text and epub. This can
                                  only be used with --builder=custom. Valid
                                  options listed at https://www.sphinx-
                                  doc.org/en/master/man/sphinx-build.html
  -v, --verbose                   increase verbosity (can be repeated)
  -q, --quiet                     -q means no sphinx status, -qq also turns
                                  off warnings
  --individualpages               [pdflatex] Enable build of PDF files for
                                  each individual page
  -h, --help                      Show this message and exit.

And here is an error. You can mark notebook cells as “expected to error” by adding a raises-exception tag to them.

this_will_error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 this_will_error

NameError: name 'this_will_error' is not defined

More features with Jupyter notebooks#

There are many other features of Jupyter notebooks to take advantage of, such as automatically generating Binder links for notebooks or connecting your content with a kernel in the cloud. For more information browse the pages in this site, and Formatting code outputs in particular.