Sphinx-Gallery

Pimp your documentation with a gallery of examples

Óscar Nájera

najera.oscar@gmail.com / Titan-C

25 August 2016 - EuroScipy - Erlangen

What is Sphinx-Gallery ?

It's an extension that builds an HTML version of any python script and puts it into an examples gallery.

You are certainly familiar with this

matplotlib_gallery.jpg http://matplotlib.org/gallery.html

Now you can have it too!!

And Better with Sphinx-Gallery

  • The Gallery building is completely automated. You just worry about: writing nice examples
  • Avoids repetition
    • Source code and documentation are the same python file
    • Every example receives a reference link name
  • Interleave prose, code and output as much as you want. Notebook styled examples
  • Your examples can be downloaded as python source files & Jupyter Notebooks
  • Visible error messages when your examples don't build correctly
  • Automatically link from your API documentation to examples using the functions

Who uses it already?

How does it look?

https://sphinx-gallery.readthedocs.io

From API to Examples

nilearn_api.jpg http://nilearn.github.io/

Setting up your Project

awesome_python_project
├── doc
│   ├── conf.py
│   ├── index.rst
│   └── Makefile
├── examples
│   ├── README.txt
│   └── plot_colors.py
...

Introduce your Gallery in examples/README.txt

.. _My_Gallery:

My Gallery
==========

Colormaps Examples
------------------

Colormap examples using Sphinx-Gallery

Your examples in Python

With the plot_ prefix Sphinx-Gallery executes the script

# -*- coding: utf-8 -*-
r"""
===============================
Colormaps alter your perception
===============================

Here I plot the function

.. math:: f(x, y) = \sin(x) + \cos(y)

with different colormaps.

"""

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi, np.pi, 300)
xx, yy = np.meshgrid(x, x)
z = np.cos(xx) + np.cos(yy)

plt.figure()
plt.imshow(z)

plt.figure()
plt.imshow(z, cmap=plt.cm.get_cmap('hot'))

plt.figure()
plt.imshow(z, cmap=plt.cm.get_cmap('Spectral'),
           interpolation='none')

# Not needed for the Gallery.
# Only for direct execution
plt.show()

################################################
# You can define blocks in your source code
# with interleaving prose.
#

print("This writes to stdout and will be",
      " displayed in the HTML file")

Setting up Sphinx-Gallery

Install it with:

$ pip install sphinx-gallery

Edit the doc/conf.py file with

import sphinx_gallery
extensions = [
    ...
    'sphinx_gallery.gen_gallery',
    ]

sphinx_gallery_conf = {
    # path to your examples scripts
    'examples_dirs' : '../examples',
    # path where to save gallery generated examples
    'gallery_dirs'  : 'auto_examples'}

Build the Documentation

$ make html

Thank you for your attention

Start using and contributing to Sphinx-Gallery