Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is plt.show() required to show a plot and when is it not?

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])
like image 612
user173729 Avatar asked Jan 29 '19 13:01

user173729


People also ask

Is PLT show () necessary?

Plotting from an IPython shell draw() . Using plt. show() in Matplotlib mode is not required.

What is PLT show () in Python?

Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. Sample Code – # sample code. import matplotlib.pyplot as plt.

Why is matplotlib not showing plot?

The issue actually stems from the matplotlib backend not being properly set, or from a missing dependency when compiling and installing matplotlib.

What is the use of matplotlib in Python explain use of plot () show () and title () functions of matplotlib?

Matplotlib is a cross-platform, data visualization and graphical plotting library for Python and its numerical extension NumPy. As such, it offers a viable open source alternative to MATLAB. Developers can also use matplotlib's APIs (Application Programming Interfaces) to embed plots in GUI applications.


Video Answer


2 Answers

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.

like image 92
Mai Hai Avatar answered Sep 28 '22 09:09

Mai Hai


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.

like image 28
Sheldore Avatar answered Sep 28 '22 09:09

Sheldore