有没有一种方法可以在 plt.show() 之后用狮身人面像显示绘图,或者在 .. plot:: 之后保持范围

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

我正在使用带有 numpydocsdoctest 和 scipy 主题的 sphinx。

当在文档字符串中使用 .. plot:: 时,所有的图都被创建,除了不显示它们被调用的地方,它们都移动到文档的末尾。有没有办法强制它内联,而不需要在 .rst 文件中重写示例?这是我的 example.py 文件文档字符串的样子:

.. 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.

或者,我尝试添加另一个 .. plot:: 方法,但它改变了范围。

.. 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

使用 make html 时会声明 x 未定义。

我 运行 提出的两个问题现已解决。其一,我没有正确显示所有更新,所以我每次都需要在 make html 之前 运行 make clean

原始问题的解决方案是在每次调用 plot.show() 时在 .. plot:: 之后添加 :context: close-figs

.. plot::
    :context: close-figs

所以我的文档字符串现在看起来像:

.. 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