How to Fix Figure Not Showing in Matplotlib Quickly
plt.show() after plotting. Adding plt.show() tells matplotlib to display the figure window, which is necessary especially outside interactive environments.Why This Happens
Matplotlib creates figures in the background but does not display them automatically in some environments. Without explicitly calling plt.show(), the figure window stays hidden. This often happens in scripts or some IDEs where the plot is not shown unless requested.
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.title('Sample Plot') # Missing plt.show() here
The Fix
To fix this, add plt.show() at the end of your plotting commands. This function opens the figure window and displays your plot. It is essential when running scripts or non-interactive environments.
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.title('Sample Plot') plt.show()
Prevention
Always include plt.show() at the end of your plotting code when working outside interactive environments like Jupyter notebooks. In Jupyter, use %matplotlib inline or %matplotlib notebook magic commands to display plots automatically. Also, avoid running plotting code in environments that suppress GUI windows without proper configuration.
Related Errors
- Empty plot window: Happens if data is empty or plot commands are incorrect; check your data and plot calls.
- Figure closes immediately: Happens if script ends right after
plt.show(); add pauses or run interactively. - No plot in Jupyter: Use
%matplotlib inlineto enable inline plots.