Configuration

Configuration and customization of sphinx-gallery is done primarily with a dictionary specified in your conf.py file. A list of the possible keys are listed below and explained in greater detail in subsequent sections.

List of config options

Most sphinx-gallery configuration options are set in the Sphinx conf.py file:

Some options can also be set or overridden on a file-by-file basis:

Some options can be set during the build execution step, e.g. using a Makefile:

And some things can be tweaked directly in CSS:

Managing multiple galleries

Sphinx-Gallery only supports up to sub-folder level in its gallery directories. This might be a limitation for you. Or you might want to have separate galleries for different purposes, an examples gallery and a tutorials gallery. For this you use in your Sphinx conf.py file a list of directories in the sphinx configuration dictionary:

sphinx_gallery_conf = {
    ...
    'examples_dirs': ['../examples', '../tutorials'],
    'gallery_dirs': ['auto_examples', 'tutorials'],
}

Keep in mind that both lists have to be of the same length.

Parsing and executing examples based on matching patterns

By default, Sphinx-Gallery will parse and add all files with a .py extension to the gallery. To ignore some files and omit them from the gallery entirely, you can use a regular expression (the default is shown here):

sphinx_gallery_conf = {
    ...
    'ignore_pattern': '__init__\.py',
}

Of the files that get parsed and added to the gallery, by default Sphinx-Gallery only executes files whose name begins with plot. However, if this naming convention does not suit your project, you can modify the pattern of filenames to build in your Sphinx conf.py. For example:

sphinx_gallery_conf = {
    ...
    'filename_pattern': '/plot_compute_',
}

will build all examples starting with plot_compute_. The key filename_pattern accepts regular expressions which will be matched with the full path of the example. This is the reason the leading '/' is required. Users are advised to use os.sep instead of '/' if they want to be agnostic to the operating system.

This option is also useful if you want to build only a subset of the examples. For example, you may want to build only one example so that you can link it in the documentation. In that case, you would do:

sphinx_gallery_conf = {
    ...
    'filename_pattern': 'plot_awesome_example\.py',
}

Here, one should escape the dot '\.' as otherwise python regular expressions matches any character. Nevertheless, as one is targeting a specific file, it would match the dot in the filename even without this escape character.

Similarly, to build only examples in a specific directory, you can do:

sphinx_gallery_conf = {
    ...
    'filename_pattern': '/directory/plot_',
}

Alternatively, you can skip executing some examples. For example, to skip building examples starting with plot_long_examples_, you would do:

sphinx_gallery_conf = {
    ...
    'filename_pattern': '/plot_(?!long_examples)',
}

As the patterns are parsed as regular expressions, users are advised to consult the regular expressions module for more details.

Note

Remember that Sphinx allows overriding conf.py values from the command line, so you can for example build a single example directly via something like:

$ sphinx-build -D sphinx_gallery_conf.filename_pattern=plot_specific_example\.py ...

Linking to documentation

Sphinx-Gallery enables you to add hyperlinks in your example scripts so that you can link the used functions to their matching online documentation. As such code snippets within the gallery appear like this

y = np.sin(x)

Have a look at this in full action in our example Sphinx-Gallery introduction.

To make this work in your documentation you need to include to the configuration dictionary within your Sphinx conf.py file:

sphinx_gallery_conf = {
    ...
    'reference_url': {
         # The module you locally document uses None
        'sphinx_gallery': None,
    }
}

To link to external modules, if you use the Sphinx extension sphinx.ext.intersphinx, no additional changes are necessary, as the intersphinx inventory will automatically be used. If you do not use intersphinx, then you should add entries that point to the directory containing searchindex.js, such as 'matplotlib': 'https://matplotlib.org'.

Adding references to examples

When documenting a given function/class, Sphinx-Gallery enables you to link to any examples that either:

  1. Use the function/instantiate the class in the code.
  2. Refer to that function/class using sphinx markup :func:/:class: in a documentation block.

The former is useful for auto-documenting functions that are used and classes that are explicitly instantiated. The latter is useful for classes that are typically implicitly returned rather than explicitly instantiated (e.g., matplotlib.axes.Axes which is most often instantiated only indirectly within function calls).

For example, we can embed a small gallery of all examples that use or refer to numpy.exp, which looks like this:

Examples using numpy.exp

For such behavior to be available, you have to activate it in your Sphinx-Gallery configuration conf.py file with:

sphinx_gallery_conf = {
    ...
    # directory where function granular galleries are stored
    'backreferences_dir'  : 'gen_modules/backreferences',

    # Modules for which function level galleries are created.  In
    # this case sphinx_gallery and numpy in a tuple of strings.
    'doc_module'          : ('sphinx_gallery', 'numpy')}

The path you specify in backreferences_dir, here we choose gen_modules/backreferences will get populated with ReStructuredText files, each of which contains a reduced version of the gallery specific to every function used across all the examples galleries and belonging to the modules listed in doc_module. Keep in mind that the path set in backreferences_dir is relative to the conf.py file.

Then within your sphinx documentation .rst files you write these lines to include this reduced version of the Gallery, which has examples in use of a specific function, in this case numpy.exp:

.. include:: gen_modules/backreferences/numpy.exp.examples
.. raw:: html

    <div style='clear:both'></div>

The include directive takes a path relative to the rst file it is called from. In the case of this documentation file (which is in the same directory as conf.py) we directly use the path declared in backreferences_dir followed by the function whose examples we want to show and the file has the .examples extension.

Using a custom default thumbnail

In case you want to use your own image for the thumbnail of examples that do not generate any plot, you can specify it by editing your Sphinx conf.py file. You need to add to the configuration dictionary a key called default_thumb_file. For example:

sphinx_gallery_conf = {
    ...
    'default_thumb_file': 'path/to/thumb/file.png',
}

Adding line numbers to examples

Line numbers can be displayed in listings by adding the global line_numbers setting:

sphinx_gallery_conf = {
    ...
    'line_numbers': True,
}

or by adding a comment to the example script, which overrides any global setting:

# sphinx_gallery_line_numbers = True

Note that for Sphinx < 1.3, the line numbers will not be consistent with the original file.

Disabling download button of all scripts

By default Sphinx-Gallery collects all python scripts and all Jupyter notebooks from each gallery into zip files which are made available for download at the bottom of each gallery. To disable this behavior add to the configuration dictionary in your conf.py file:

sphinx_gallery_conf = {
    ...
    'download_all_examples': False,
}

Choosing the thumbnail image

For examples that generate multiple figures, the default behavior will use the first figure created in each as the thumbnail image displayed in the gallery. To change the thumbnail image to a figure generated later in an example script, add a comment to the example script to specify the number of the figure you would like to use as the thumbnail. For example, to use the 2nd figure created as the thumbnail:

# sphinx_gallery_thumbnail_number = 2

The default behavior is sphinx_gallery_thumbnail_number = 1. See Choosing the thumbnail figure for an example of this functionality.

Building without executing examples

Sphinx-Gallery can parse all your examples and build the gallery without executing any of the scripts. This is just for speed visualization processes of the gallery and the size it takes your website to display, or any use you can imagine for it. To achieve this you need to pass the no plot option in the build process by modifying your Makefile with:

html-noplot:
    $(SPHINXBUILD) -D plot_gallery=0 -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
    @echo
    @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

Remember that for Makefile white space is significant and the indentation are tabs and not spaces.

Alternatively, you can add the plot_gallery option to the sphinx_gallery_conf dictionary inside your conf.py to have it as a default:

sphinx_gallery_conf = {
    ...
    'plot_gallery': 'False',
}

The highest precedence is always given to the -D flag of the sphinx-build command.

Image scrapers

By default, at the end of each code block Sphinx-gallery will detect new matplotlib.pyplot figures and turn them into images. This behavior is equivalent to the default of:

sphinx_gallery_conf = {
    ...
    'image_scrapers': ('matplotlib',),
}

Built-in support is also provided for finding Mayavi figures. To enable this feature, you can do:

sphinx_gallery_conf = {
    ...
    'image_scrapers': ('matplotlib', 'mayavi'),
}

Note

The parameter find_mayavi_figures which can also be used to extract Mayavi figures is deprecated in version 0.2+, and will be removed in a future release.

Custom scrapers

Note

The API for custom scrapers is currently experimental.

You can also add your own custom function (or callable class instance) to this list. See sphinx_gallery.scrapers.matplotlib_scraper() for a description of the interface. Here is pseudocode for what this function and sphinx_gallery.scrapers.mayavi_scraper() do under the hood, which uses sphinx_gallery.scrapers.figure_rst() to create standardized RST:

def mod_scraper(block, block_vars, gallery_conf)
    import mymod
    image_names = list()
    image_path_iterator = block_vars['image_path_iterator']
    for fig, image_path in zip(mymod.get_figures(), image_path_iterator):
        fig.save_png(image_path)
        image_names.append(image_path)
    mymod.close('all')
    return figure_rst(image_names, gallery_conf['src_dir'])

For example, a naive class to scrape any new PNG outputs in the current directory could do, e.g.:

import glob
import shutil
from sphinx_gallery.gen_rst import figure_rst


class PNGScraper(object):
    def __init__(self):
        self.seen = set()

    def __call__(self, block, block_vars, gallery_conf):
        pngs = sorted(glob.glob(os.path.join(os.getcwd(), '*.png'))
        image_names = list()
        image_path_iterator = block_vars['image_path_iterator']
        for png in pngs:
            if png not in seen:
                seen |= set(png)
                image_names.append(image_path_iterator.next())
                shutil.copyfile(png, image_names[-1])
        return figure_rst(image_names, gallery_conf['src_dir'])


sphinx_gallery_conf = {
    ...
    'image_scrapers': ('matplotlib', PNGScraper()),
}

If you have an idea for a scraper that is likely to be useful to others (e.g., a fully functional image-file-detector, or one for another visualization libarry), feel free to contribute it on GitHub!

Resetting modules

By default, at the end of each file matplotlib is reset using matplotlib.pyplot.rcdefaults() and seaborn is reset by trying to unload the module from sys.modules. This is equivalent to the entries:

sphinx_gallery_conf = {
    ...
    'reset_modules': ('matplotlib', 'seaborn'),
}

You can also add your own custom function to this tuple. The function takes two variables, the gallery_conf dict and the fname, which on the first call is the directory name being processed, and then the names of all files within that directory. For example, to reset matplotlib to always use the ggplot style, you could do:

def reset_mpl(gallery_conf, fname):
    from matplotlib import style
    style.use('ggplot')


sphinx_gallery_conf = {
    ...
    'reset_modules': (reset_mpl,),
}

Note

Using resetters such as reset_mpl that deviate from standard behaviors that users will experience when manually running examples themselves is discouraged due to the inconsistency that results between the rendered examples and local outputs.

Minimal reported time

By default, Sphinx-gallery logs and embeds in the html output the time it took to run each script. If the majority of your examples runs quickly, you may not need this information.

The min_reported_time configuration can be set to a number of seconds. The duration of scripts that ran faster than that amount will not be logged nor embedded in the html output.