Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
When is plt.Show() required to show a plot and when is it not?
When working with Matplotlib plots, understanding when to use plt.show() is crucial. The requirement depends on your environment ? whether you're in an interactive Python session, a Jupyter notebook, or running a script.
Interactive vs Non-Interactive Environments
In interactive environments like Jupyter notebooks or IPython, plots often display automatically without calling plt.show(). In non-interactive environments like regular Python scripts, you must call plt.show() to display the plot.
Basic Example Without plt.show()
In Jupyter notebooks, this code displays the plot automatically:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
[Displays plot automatically in Jupyter]
Using plt.show() Explicitly
For Python scripts or when you want explicit control, use plt.show():
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.cos(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, 'b-', linewidth=2)
plt.title("Cosine Wave")
plt.grid(True)
plt.show()
[Displays plot in a popup window]
Using fig.show() vs plt.show()
The fig.show() method is used with figure objects, while plt.show() works with the current figure:
import matplotlib.pyplot as plt
import numpy as np
# Create figure object
fig, ax = plt.subplots(figsize=(7, 4))
x = np.linspace(0, 10, 50)
ax.plot(x, x**2, 'r-', label='x²')
ax.set_title("Quadratic Function")
ax.legend()
# Using fig.show() - non-blocking
fig.show()
# Using plt.show() - blocks execution until window closed
plt.show()
[Displays plot with both methods]
When Each Method is Required
| Environment | plt.show() Required? | Best Practice |
|---|---|---|
| Jupyter Notebook | No (automatic display) | Optional for explicit control |
| Python Script | Yes (mandatory) | Always use plt.show() |
| IPython Interactive | Sometimes | Use for explicit display |
Conclusion
Use plt.show() in Python scripts to display plots. In interactive environments like Jupyter, it's optional but provides explicit control. Use fig.show() for non-blocking display when working with figure objects.
