Search code examples
python-sphinxnumpydoc

Is there a method for displaying plots after plt.show() with sphinx or keep scope after .. plot::


I am using sphinx with numpydocs, doctest, and the scipy theme.

When using .. plot:: in a docstring, the plots are all created, except instead of showing where they are called, they all move to the end of the documentation. Is there a way to force it inline, without needed to rewrite the example in an .rst file? This is what my example.py file docstring looks like:

.. plot::

    >>> import numpy as np
    >>> import matplotlib.pylab as plt

    # commentary breaking the block 
    Finished Imports

    >>> x = np.linspace(-np.pi*2, np.pi*2, 2000)
    >>> y = np.sin(x)
    >>> plt.plot(x, y)#doctest: +SKIP
    >>> plt.show()#doctest: +SKIP

First plot should be here

    >>> x2 = x
    >>> plt.plot(x2, y)#doctest: +SKIP
    >>> plt.show()#doctest: +SKIP

Second plot should be here

....

But both are here.

Alternatively, I tried adding another .. plot:: method but it changes scope.

.. plot::

    >>> import numpy as np
    >>> import matplotlib.pylab as plt

    # commentary breaking the block 
    Finished Imports

    >>> x = np.linspace(-np.pi*2, np.pi*2, 2000)
    >>> y = np.sin(x)
    >>> plt.plot(x, y)#doctest: +SKIP
    >>> plt.show()#doctest: +SKIP

First plot should be here

.. plot::

    >>> x2 = x
    >>> plt.plot(x2, y)#doctest: +SKIP
    >>> plt.show()#doctest: +SKIP

Which when using make html will state x is not defined.


Solution

  • There were two issues I ran into that are now resolved. For one, I wasn't getting all the updates correctly displayed, so I need to run make clean before make html each time.

    The solution to the original problem though is to add :context: close-figs after .. plot:: each time plot.show() is called.

    .. plot::
        :context: close-figs
    

    So my docstring now looks like:

    .. plot::
        :context: close-figs
    
        >>> import numpy as np
        >>> import matplotlib.pylab as plt
    
        # commentary breaking the block 
        Finished Imports
    
        >>> x = np.linspace(-np.pi*2, np.pi*2, 2000)
        >>> y = np.sin(x)
        >>> plt.plot(x, y)#doctest: +SKIP
        >>> plt.show()#doctest: +SKIP
    
    .. plot::
        :context: close-figs
    
    First plot shows here
    
        >>> x2 = x
        >>> plt.plot(x2, y)#doctest: +SKIP
        >>> plt.show()#doctest: +SKIP
    
    .. plot::
        :context: close-figs
    
    Second plot shows here