When is plt.show() required to show a plot and whe

2020-07-20 03:51发布

问题:

Since the following code will show a plot without plt.show(), what is the point of plt.show()?

Please tell me when plt.show() is required as this would allow me to appreciate the intricacy of matplotlib better.

N.B.: I'm using this in Spyder (Anaconda)

import matplotlib.pyplot as plt
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])

回答1:

To require or not required depending on where your script is.

There are 2 contexts.

  1. Matplotlib is used in a terminal or scripts, plt.show() is a must.

  2. Matplotlib is used in a IPython shell or a notebook (ex: Kaggle), plt.show() is unnecessary.



回答2:

It seems either you are in an interactive mode or are using a JuPyter notebook, in both the cases plt.show() being rendered redundant (check the bold highlighted doc below)

From the official docs

Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt.

In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.

A single experimental keyword argument, block, may be set to True or False to override the blocking behavior described above.