How to Show Plot in Matplotlib: Simple Guide
To show a plot in
matplotlib, use the plt.show() function after creating your plot. This command opens a window displaying the plot so you can see the visual output.Syntax
The basic syntax to display a plot in matplotlib is:
plt.plot(): Creates the plot with your data.plt.show(): Opens a window to display the plot.
You must call plt.show() after all plotting commands to see the result.
python
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) # Create a simple line plot plt.show() # Display the plot window
Output
A window opens showing a line graph with points at y-values 1, 2, 3, 4
Example
This example creates a simple line plot and shows it using plt.show(). The plot window will display a line connecting the points.
python
import matplotlib.pyplot as plt x = [0, 1, 2, 3] y = [10, 20, 25, 30] plt.plot(x, y) # Plot x vs y plt.title('Simple Line Plot') # Add a title plt.xlabel('X axis') # Label x-axis plt.ylabel('Y axis') # Label y-axis plt.show() # Show the plot
Output
A window opens showing a line plot with labeled axes and title
Common Pitfalls
One common mistake is forgetting to call plt.show(), which means the plot will not appear. Another is calling plt.show() before finishing all plot commands, which can cause incomplete plots.
Also, in some environments like Jupyter notebooks, plots may display automatically without plt.show(), but it is good practice to include it for consistency.
python
import matplotlib.pyplot as plt # Wrong: Missing plt.show(), plot will not display plt.plot([1, 2, 3]) # Right: Call plt.show() to display plt.plot([1, 2, 3]) plt.show()
Output
Only the second plot call opens a window showing the line plot
Quick Reference
Remember these tips to show plots correctly:
- Always call
plt.show()after plotting commands. - Prepare your plot fully before calling
plt.show(). - In scripts,
plt.show()pauses execution until you close the plot window. - In interactive environments, plots may show automatically but use
plt.show()for clarity.
Key Takeaways
Use plt.show() to display your matplotlib plot window.
Call plt.show() after all plotting commands to see the complete plot.
Forgetting plt.show() means no plot window appears in scripts.
In notebooks, plots may show automatically but plt.show() is best practice.
plt.show() pauses script execution until the plot window is closed.