Python Forum

Full Version: matplotlib.pyplot.show
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am starting to learn about plotting and have a question about what plt.show() does.

I get the definition "The show() function in pyplot module of matplotlib library is used to display all figures", but can never find what figures this refers to. The two examples I looked at:
# sample code 
import matplotlib.pyplot as plt  
    
plt.plot([1, 2, 3, 4], [16, 4, 1, 8])  
plt.show()  
and

# Implementation of matplotlib function 
import matplotlib.pyplot as plt 
import numpy as np 
  
fig = plt.figure() 
x = np.arange(20) / 50
y = (x + 0.1)*2
  
val1 = [True, False] * 10
val2 = [False, True] * 10
  
plt.errorbar(x, y,  
             xerr = 0.1,  
             xlolims = True,  
             label ='Line 1') 
  
y = (x + 0.3)*3
  
plt.errorbar(x + 0.6, y,  
             xerr = 0.1, 
             xuplims = val1, 
             xlolims = val2, 
             label ='Line 2') 
  
y = (x + 0.6)*4
plt.errorbar(x + 1.2, y, 
             xerr = 0.1,  
             xuplims = True, 
             label ='Line 3') 
  
plt.legend() 
  
fig.suptitle('matplotlib.pyplot.show() Example') 
plt.show()
Seem to be not very good examples, because when I comment out the plt.show() lines and execute the code again, it displays exactly the same result as before, when plt.show() was not commented out.

Can someone explain to me (as if I were a fourth grader) what the purpose of plt.show() is?

Thanks in advance.
Hi Alienspecimen

Interesting question, I found there is an interactive mode, in which plots are automatically displayed. You might be working in an environment which defaults to interactive mode. If you were to write a program and run it as a script, you typically would not be interactive mode. Here is the official docs and related functions:

https://matplotlib.org/stable/api/_as_ge...ive%20mode

Also see Appendix B in the below:

https://realpython.com/python-matplotlib-guide/
(Feb-26-2021, 03:20 AM)Alienspecimen Wrote: [ -> ]it displays exactly the same result as before, when plt.show() was not commented out.
No it depend of what environment(Editor/IDE/Notebook) you run code in.
If run code from command line it will display nothing.
The purpose plt.show() is to generate a way to display the result when no external environment is used.

So if put code in a Notebook it disaply fine without plt.show().
But if i run same code from command line,it will display nothing without plt.show().
G:\div_code\div
λ python mp_test.py
# Nothing is shown