How to Use Matplotlib in Jupyter Notebooks: Simple Guide
To use
matplotlib in Jupyter notebooks, first import it with import matplotlib.pyplot as plt. Then, use %matplotlib inline to display plots inside the notebook cells automatically.Syntax
Here is the basic syntax to use matplotlib in Jupyter notebooks:
%matplotlib inline: This magic command makes plots appear inside the notebook.import matplotlib.pyplot as plt: Imports the plotting module with a short name.plt.plot(): Creates a plot with your data.plt.show(): Displays the plot (optional in Jupyter with inline magic).
python
%matplotlib inline import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Example
This example shows how to plot a simple line graph inside a Jupyter notebook using matplotlib.
python
%matplotlib inline import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4] y = [0, 1, 4, 9, 16] plt.plot(x, y, marker='o', linestyle='-', color='blue') plt.title('Simple Line Plot') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show()
Output
A blue line plot with points marked by circles, titled 'Simple Line Plot', with labeled X and Y axes.
Common Pitfalls
Common mistakes when using matplotlib in Jupyter include:
- Not running
%matplotlib inline, so plots do not display automatically. - Forgetting to import
matplotlib.pyplotasplt. - Calling
plt.show()outside Jupyter or forgetting it in other environments. - Using outdated magic commands like
%pylab inlinewhich is discouraged.
python
import matplotlib.pyplot as plt # Wrong: No magic command, plot may not show automatically plt.plot([1, 2, 3], [4, 5, 6]) # Right: Use magic command to show plots inline %matplotlib inline plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Quick Reference
Here is a quick cheat sheet for using matplotlib in Jupyter:
| Command | Purpose |
|---|---|
| %matplotlib inline | Show plots inside notebook cells |
| import matplotlib.pyplot as plt | Import plotting functions |
| plt.plot(x, y) | Create a line plot |
| plt.title('Title') | Add a title to the plot |
| plt.xlabel('X label') | Label the X axis |
| plt.ylabel('Y label') | Label the Y axis |
| plt.show() | Display the plot explicitly |
Key Takeaways
Always run %matplotlib inline in Jupyter to display plots inside cells.
Import matplotlib.pyplot as plt to access plotting functions easily.
Use plt.plot() to create plots and plt.show() to display them if needed.
Label your plots with titles and axis labels for clarity.
Avoid outdated magic commands and remember to import before plotting.