How to Fix Matplotlib Plot Not Showing in Python
In this tutorial, you'll learn about How to Fix Matplotlib Plot Not Showing in Python. We cover key concepts, practical examples, and best practices.
Matplotlib plots do not appear when plt.show() is not called, the wrong backend is configured, or the display is not properly initialized.
The Wrong Way
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("My Plot")
# Missing plt.show()
Running this script produces no visible output -- no plot window appears.
The Right Way
Call plt.show() at the end:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("My Plot")
plt.show()
This opens an interactive window displaying the plot.
Step-by-Step Fix
1. Add plt.show() at the end
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.show()
2. Use interactive mode for immediate display
import matplotlib.pyplot as plt
plt.ion() # interactive mode on
plt.plot([1, 2, 3], [4, 5, 6])
plt.draw()
plt.pause(0.001) # render the plot
3. Check the matplotlib backend
import matplotlib
print(matplotlib.get_backend())
# For Jupyter/notebook environments
matplotlib.use('TkAgg') # or 'Qt5Agg', 'Agg' for file-only
4. Save to file instead
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
print("Plot saved to plot.png")
5. Configure for Jupyter notebooks
%matplotlib inline # in Jupyter cell
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Prevention Tips
- Always call
plt.show()at the end of plotting scripts. - Use
plt.savefig()to generate files when no display is available. - Set
MPLBACKENDenvironment variable for headless environments. - Use
%matplotlib inlinein Jupyter notebooks. - Use
matplotlib.use('Agg')for server-side or CI environments.
Common Mistakes with matplotlib not showing
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro