Issue
The function shown below displays a line plot using Matplotlib. The docstring of the function contains an example of using the function with a list of numbers. I'm using the Sphinx make html
command to create documentation for this function. I also use Sphinx to test the docstring using make doctest
. However, doctest pauses when it tests this function because it displays a window containing the plot figure. I have to manually close the plot figure window for doctest to continue running. Is there a better way to use doctest with docstrings that contain Matplotlib examples?
import matplotlib.pyplot as plt
def plot_numbers(x):
"""
Show a line plot of numbers.
Parameters
----------
x : list
Numbers to plot.
Example
-------
>>> import calc
>>> x = [1, 2, 5, 6, 8.1, 7, 10.5, 12]
>>> calc.plot_numbers(x)
"""
_, ax = plt.subplots()
ax.plot(x, marker="o", mfc="red", mec="red")
ax.set_xlabel("Label for x-axis")
ax.set_ylabel("Label for y-axis")
ax.set_title("Title of the plot")
plt.show()
Solution
Ideally you would structure the plotting routine so the user could provide their own axes (and/or figure). I wouldn't call plt.show
for the user - how do you know they are ready to display the figure?
import matplotlib.pyplot as plt
def plot_numbers(x, *, ax=None):
"""
Show a line plot of numbers.
Parameters
----------
x : list
Numbers to plot.
ax: Axes
Optional Matplotlib Axes to plot the numbers on.
Example
-------
>>> import calc
>>> x = [1, 2, 5, 6, 8.1, 7, 10.5, 12]
>>> calc.plot_numbers(x)
"""
if ax is None:
_, ax = plt.subplots()
ax.plot(x, marker="o", mfc="red", mec="red")
ax.set_xlabel("Label for x-axis")
ax.set_ylabel("Label for y-axis")
ax.set_title("Title of the plot")
return ax
See also https://matplotlib.org/stable/users/explain/quick_start.html#making-a-helper-functions though note in that suggestion, ax
is required.
Answered By - Jody Klymak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.