How to import a package in plot directive

How can I import a package within a plot directive? I noticed there’s a run_code command, which seems like what I need, but it’s deprecated:

[Deprecated] Import a Python module from a path, and run the function given by name, if function_name is not None.

Specifically, I’m trying to import SciPy, and get this error:

ModuleNotFoundError: No module named 'scipy'

Perhaps I need to use plot_working_directory

By default, the working directory will be changed to the directory of the example, so the code can get at its data files, if any. Also its path will be added to sys.path so it can import any helper modules sitting beside it. This configuration option can be used to specify a central directory (also added to sys.path) where data files and helper modules for all code are located.

but it’s unclear to me what directory I should set.


In the SymPy docs, this produces a plot fine:

.. plot::
  :format: doctest
  :include-source: True
  :context: close-figs

  >>> from sympy import symbols, lambdify
  >>> import numpy as np
  >>> #import scipy.integrate
  >>> import matplotlib.pyplot as plt
  >>> plt.plot([11, 12, 13], [16, 15, 12]) # doctest: +SKIP

But when I uncomment the scipy import, it fails.

Turned out that SciPy needed to be a dependency for the docs, by adding scipy to doc/requirements.txt where doc is the documentation folder.