Skip to content

Sphinx extension plot_directive not able to detect function #20656

Closed
@Nateckert

Description

@Nateckert

Bug report

Bug summary

When writing a generical code to generate plots with sphinx documentation, this function cannot be called by other functions from the documentation in the same file

Code for reproduction

Repository layout:

  • docs
    • source
      • pyplots
        • test.py
      • conf.py
      • index.rst
  • package

Content of file test.py

import matplotlib.pyplot as plt


def generate_plot_according_to_step(step):

    plt.figure()

    plt.plot([1, 2], [2, 3])

    if step >= 1:
        plt.title("Adding a title")

    if step >= 2:
        plt.suptitle('Adding a suptitle')

    plt.show()


def step0():
    generate_plot_according_to_step(0)


def step1():
    generate_plot_according_to_step(1)


def step2():
    generate_plot_according_to_step(2)

Content of conf.py :

extensions = [
        'sphinx.ext.autodoc',
        'matplotlib.sphinxext.plot_directive'
]

Then when referencing the steps functions in docstring anywhere in the package, such as:

"""
.. plot:: pyplots/test.py step0

.. plot:: pyplots/test.py step1

.. plot:: pyplots/test.py step2

"""

Actual outcome

When building the doc through the following steps:

cd .\docs

sphinx-quickstart

sphinx-apidoc -f -o source/ ../

.\make.bat html

The following message arise

 WARNING: Exception occurred in plotting test
 from path\to\repository\docs\source\pyplots/test.py:
Traceback (most recent call last):
  File "path\to\repository\.venv\lib\site-packages\matplotlib\sphinxext\plot_directive.py", line 485, in run_code
    exec(function_name + "()", ns)
  File "<string>", line 1, in <module>
NameError: name 'step0' is not defined

Expected outcome

It seems that it is not possible to use a generical function such as the one presented to generate documentation.
Either it is considered a bug and should be fixed or the error message should be more explicit, as it is currently inaccurate, as the step functions exists

Matplotlib version

  • Operating system: Windows 10
  • Matplotlib version (import matplotlib; print(matplotlib.__version__)): 3.4.2
  • Matplotlib backend (print(matplotlib.get_backend())): TkAgg
  • Python version: 3.9.5
  • Other libraries: Sphinx 4.0.2

Every library has been installed through pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions