When we have subplots in Matplotlib, do we call plt.show() for each one?

Question

When we have subplots in Matplotlib, do we call plt.show() for each one?

Answer

No, we only need to call plt.show() one time after we create all the subplots we want to display.

If you do, however, have multiple plt.show() calls, you will see that the first time you call it, it will only display the subplots before that call. Then, the next plt.show() call will also show all previously defined subplots, including the ones shown on the previous plot. As a result, doing multiple plt.show() calls might not be a good idea.

Feel free to try this out, and see what happens!

3 Likes

Hi ! I dont think the following lines are true:

‘…the next plt.show() call will also show all previously defined subplots, including the ones shown on the previous plot…’. On your platform, that is what it is doing…but trying it on Jupyter Notebook, I find only the plots that have not been displayed previously are ‘active’ and displayed.

From all the research I have done - plt.show() - ‘…displays the active plots and clears them.’ This is proven by doing a plt.savefig() before a plt.show() - whereby the graph IS stored in the savefig chart and if a savefig() is done after plt.show() - then the figure saved by savefig() has nothing in it.
And therefore, the plt.clf() call being added after plt.show() in all previous excercises is actually redundant.

Unless - all above is moot due to revisions in the matplotlib library since this question was posted.

Was just revising my Data Science concepts and came across this question…so adding my two cents.

Yes. It’s different outside of the LE. If you’re using Jupyter or Colab, you have to run the cells in order from top to bottom…and the one where your plot code is (obv).

There is a block= parameter to plt.show() that takes a boolean,

See:
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.show.html

plt.savefig() saves the plot to a specified image file type (.png, etc) and doesn’t display it. Like if you wanted to use the figure/plot in another doc like in Slides or powerpoint. And, yes, you’re correct that you have to save it before showing the plot.

See: matplotlib.pyplot.savefig — Matplotlib 3.8.2 documentation

plt.clf() clears the plots/figure.