This page was generated from doc/gallery/thumbnail-from-conf-py.ipynb. Interactive online version: Binder badge. Download notebook.

Specifying Thumbnails in conf.py

This notebook doesn’t contain a nbsphinx-thumbnail cell tag nor cell metadata. Instead, in the file conf.py, a thumbnail is specified (via the nbsphinx_thumbnails option), which will be used in the gallery.

The keys in the nbsphinx_thumbnails dictionary can contain wildcards, which behave very similarly to the html_sidebars option.

The thumbnail files can be local image files somewhere in the source directory, but you’ll need to create at least one link to them in order to copy them to the HTML output directory.

You can also use files from the _static directory (which contains all files in your html_static_path).

If you want, you can also use files from the _images directory, which contains all notebook outputs.

To demonstrate this feature, we are creating an image file here:

[1]:
import matplotlib.pyplot as plt
[2]:
fig, ax = plt.subplots()
ax.plot([4, 8, 15, 16, 23, 42])
fig.savefig('a-local-file.png')
plt.close()  # avoid plotting the figure
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[2], line 1
----> 1 fig, ax = plt.subplots()
      2 ax.plot([4, 8, 15, 16, 23, 42])
      3 fig.savefig('a-local-file.png')

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:1450, in subplots(nrows, ncols, sharex, sharey, squeeze, width_ratios, height_ratios, subplot_kw, gridspec_kw, **fig_kw)
   1304 def subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True,
   1305              width_ratios=None, height_ratios=None,
   1306              subplot_kw=None, gridspec_kw=None, **fig_kw):
   1307     """
   1308     Create a figure and a set of subplots.
   1309
   (...)
   1448
   1449     """
-> 1450     fig = figure(**fig_kw)
   1451     axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
   1452                        squeeze=squeeze, subplot_kw=subplot_kw,
   1453                        gridspec_kw=gridspec_kw, height_ratios=height_ratios,
   1454                        width_ratios=width_ratios)
   1455     return fig, axs

File /usr/lib/python3/dist-packages/matplotlib/_api/deprecation.py:454, in make_keyword_only.<locals>.wrapper(*args, **kwargs)
    448 if len(args) > name_idx:
    449     warn_deprecated(
    450         since, message="Passing the %(name)s %(obj_type)s "
    451         "positionally is deprecated since Matplotlib %(since)s; the "
    452         "parameter will become keyword-only %(removal)s.",
    453         name=name, obj_type=f"parameter of {func.__name__}()")
--> 454 return func(*args, **kwargs)

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:783, in figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, clear, **kwargs)
    773 if len(allnums) == max_open_warning >= 1:
    774     _api.warn_external(
    775         f"More than {max_open_warning} figures have been opened. "
    776         f"Figures created through the pyplot interface "
   (...)
    780         f"Consider using `matplotlib.pyplot.close()`.",
    781         RuntimeWarning)
--> 783 manager = new_figure_manager(
    784     num, figsize=figsize, dpi=dpi,
    785     facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
    786     FigureClass=FigureClass, **kwargs)
    787 fig = manager.canvas.figure
    788 if fig_label:

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:358, in new_figure_manager(*args, **kwargs)
    356 def new_figure_manager(*args, **kwargs):
    357     """Create a new figure manager instance."""
--> 358     _warn_if_gui_out_of_main_thread()
    359     return _get_backend_mod().new_figure_manager(*args, **kwargs)

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:336, in _warn_if_gui_out_of_main_thread()
    334 def _warn_if_gui_out_of_main_thread():
    335     warn = False
--> 336     if _get_required_interactive_framework(_get_backend_mod()):
    337         if hasattr(threading, 'get_native_id'):
    338             # This compares native thread ids because even if Python-level
    339             # Thread objects match, the underlying OS thread (which is what
    340             # really matters) may be different on Python implementations with
    341             # green threads.
    342             if threading.get_native_id() != threading.main_thread().native_id:

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:207, in _get_backend_mod()
    198 """
    199 Ensure that a backend is selected and return it.
    200
    201 This is currently private, but may be made public in the future.
    202 """
    203 if _backend_mod is None:
    204     # Use __getitem__ here to avoid going through the fallback logic (which
    205     # will (re)import pyplot and then call switch_backend if we need to
    206     # resolve the auto sentinel)
--> 207     switch_backend(dict.__getitem__(rcParams, "backend"))
    208 return _backend_mod

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:265, in switch_backend(newbackend)
    262         rcParamsOrig["backend"] = "agg"
    263         return
--> 265 backend_mod = importlib.import_module(
    266     cbook._backend_module_name(newbackend))
    268 required_framework = _get_required_interactive_framework(backend_mod)
    269 if required_framework is not None:

File /usr/lib/python3.12/importlib/__init__.py:90, in import_module(name, package)
     88             break
     89         level += 1
---> 90 return _bootstrap._gcd_import(name[level:], package, level)

File <frozen importlib._bootstrap>:1387, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1360, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:1310, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:488, in _call_with_frames_removed(f, *args, **kwds)

File <frozen importlib._bootstrap>:1387, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1360, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:1331, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:935, in _load_unlocked(spec)

File <frozen importlib._bootstrap_external>:995, in exec_module(self, module)

File <frozen importlib._bootstrap>:488, in _call_with_frames_removed(f, *args, **kwds)

File /usr/lib/python3/dist-packages/matplotlib_inline/__init__.py:1
----> 1 from . import backend_inline, config  # noqa
      3 __version__ = "0.2.1"
      5 # we can't ''.join(...) otherwise finding the version number at build time requires
      6 # import which introduces IPython and matplotlib at build time, and thus circular
      7 # dependencies.

File /usr/lib/python3/dist-packages/matplotlib_inline/backend_inline.py:236
    231                 ip.events.unregister("post_run_cell", configure_once)
    233             ip.events.register("post_run_cell", configure_once)
--> 236 _enable_matplotlib_integration()
    239 def _fetch_figure_metadata(fig):
    240     """Get some metadata to help with displaying a figure."""

File /usr/lib/python3/dist-packages/matplotlib_inline/backend_inline.py:218, in _enable_matplotlib_integration()
    216     backend = matplotlib.get_backend(auto_select=False)
    217 else:
--> 218     backend = matplotlib.rcParams._get("backend")
    220 if ip and backend in ("inline", "module://matplotlib_inline.backend_inline"):
    221     from IPython.core.pylabtools import activate_matplotlib

AttributeError: 'RcParams' object has no attribute '_get'

Please note that the previous cell doesn’t have any outputs, but it has generated a file named a-local-file.png in the notebook’s directory.

We have to create a link to this file (which is a good idea anyway): a-local-file.png.

Now we can use this file in our conf.py like this:

nbsphinx_thumbnails = {
    'gallery/thumbnail-from-conf-py': 'gallery/a-local-file.png',
}

Please note that the notebook name does not contain the .ipynb suffix.

Note that the following plot is not used as a thumbnail because the nbsphinx_thumbnails setting overrides the default behavior.

[3]:
fig, ax = plt.subplots(figsize=[6, 3])
ax.plot([4, 9, 7, 20, 6, 33, 13, 23, 16, 62, 8], 'r:');
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[3], line 1
----> 1 fig, ax = plt.subplots(figsize=[6, 3])
      2 ax.plot([4, 9, 7, 20, 6, 33, 13, 23, 16, 62, 8], 'r:');

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:1450, in subplots(nrows, ncols, sharex, sharey, squeeze, width_ratios, height_ratios, subplot_kw, gridspec_kw, **fig_kw)
   1304 def subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True,
   1305              width_ratios=None, height_ratios=None,
   1306              subplot_kw=None, gridspec_kw=None, **fig_kw):
   1307     """
   1308     Create a figure and a set of subplots.
   1309
   (...)
   1448
   1449     """
-> 1450     fig = figure(**fig_kw)
   1451     axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
   1452                        squeeze=squeeze, subplot_kw=subplot_kw,
   1453                        gridspec_kw=gridspec_kw, height_ratios=height_ratios,
   1454                        width_ratios=width_ratios)
   1455     return fig, axs

File /usr/lib/python3/dist-packages/matplotlib/_api/deprecation.py:454, in make_keyword_only.<locals>.wrapper(*args, **kwargs)
    448 if len(args) > name_idx:
    449     warn_deprecated(
    450         since, message="Passing the %(name)s %(obj_type)s "
    451         "positionally is deprecated since Matplotlib %(since)s; the "
    452         "parameter will become keyword-only %(removal)s.",
    453         name=name, obj_type=f"parameter of {func.__name__}()")
--> 454 return func(*args, **kwargs)

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:783, in figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, clear, **kwargs)
    773 if len(allnums) == max_open_warning >= 1:
    774     _api.warn_external(
    775         f"More than {max_open_warning} figures have been opened. "
    776         f"Figures created through the pyplot interface "
   (...)
    780         f"Consider using `matplotlib.pyplot.close()`.",
    781         RuntimeWarning)
--> 783 manager = new_figure_manager(
    784     num, figsize=figsize, dpi=dpi,
    785     facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
    786     FigureClass=FigureClass, **kwargs)
    787 fig = manager.canvas.figure
    788 if fig_label:

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:358, in new_figure_manager(*args, **kwargs)
    356 def new_figure_manager(*args, **kwargs):
    357     """Create a new figure manager instance."""
--> 358     _warn_if_gui_out_of_main_thread()
    359     return _get_backend_mod().new_figure_manager(*args, **kwargs)

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:336, in _warn_if_gui_out_of_main_thread()
    334 def _warn_if_gui_out_of_main_thread():
    335     warn = False
--> 336     if _get_required_interactive_framework(_get_backend_mod()):
    337         if hasattr(threading, 'get_native_id'):
    338             # This compares native thread ids because even if Python-level
    339             # Thread objects match, the underlying OS thread (which is what
    340             # really matters) may be different on Python implementations with
    341             # green threads.
    342             if threading.get_native_id() != threading.main_thread().native_id:

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:207, in _get_backend_mod()
    198 """
    199 Ensure that a backend is selected and return it.
    200
    201 This is currently private, but may be made public in the future.
    202 """
    203 if _backend_mod is None:
    204     # Use __getitem__ here to avoid going through the fallback logic (which
    205     # will (re)import pyplot and then call switch_backend if we need to
    206     # resolve the auto sentinel)
--> 207     switch_backend(dict.__getitem__(rcParams, "backend"))
    208 return _backend_mod

File /usr/lib/python3/dist-packages/matplotlib/pyplot.py:265, in switch_backend(newbackend)
    262         rcParamsOrig["backend"] = "agg"
    263         return
--> 265 backend_mod = importlib.import_module(
    266     cbook._backend_module_name(newbackend))
    268 required_framework = _get_required_interactive_framework(backend_mod)
    269 if required_framework is not None:

File /usr/lib/python3.12/importlib/__init__.py:90, in import_module(name, package)
     88             break
     89         level += 1
---> 90 return _bootstrap._gcd_import(name[level:], package, level)

File <frozen importlib._bootstrap>:1387, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1360, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:1310, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:488, in _call_with_frames_removed(f, *args, **kwds)

File <frozen importlib._bootstrap>:1387, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1360, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:1331, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:935, in _load_unlocked(spec)

File <frozen importlib._bootstrap_external>:995, in exec_module(self, module)

File <frozen importlib._bootstrap>:488, in _call_with_frames_removed(f, *args, **kwds)

File /usr/lib/python3/dist-packages/matplotlib_inline/__init__.py:1
----> 1 from . import backend_inline, config  # noqa
      3 __version__ = "0.2.1"
      5 # we can't ''.join(...) otherwise finding the version number at build time requires
      6 # import which introduces IPython and matplotlib at build time, and thus circular
      7 # dependencies.

File /usr/lib/python3/dist-packages/matplotlib_inline/backend_inline.py:236
    231                 ip.events.unregister("post_run_cell", configure_once)
    233             ip.events.register("post_run_cell", configure_once)
--> 236 _enable_matplotlib_integration()
    239 def _fetch_figure_metadata(fig):
    240     """Get some metadata to help with displaying a figure."""

File /usr/lib/python3/dist-packages/matplotlib_inline/backend_inline.py:218, in _enable_matplotlib_integration()
    216     backend = matplotlib.get_backend(auto_select=False)
    217 else:
--> 218     backend = matplotlib.rcParams._get("backend")
    220 if ip and backend in ("inline", "module://matplotlib_inline.backend_inline"):
    221     from IPython.core.pylabtools import activate_matplotlib

AttributeError: 'RcParams' object has no attribute '_get'