How to Display Matplotlib Inline in Jupyter Notebooks
To display matplotlib plots inline in Jupyter notebooks, use the
%matplotlib inline magic command at the start of your notebook. This command ensures that plots appear directly below the code cells without needing to call plt.show() explicitly.Syntax
The syntax to display matplotlib plots inline in Jupyter notebooks is simple:
%matplotlib inline: This is a magic command that tells Jupyter to show plots inside the notebook.import matplotlib.pyplot as plt: This imports the plotting library.plt.plot(): This creates a plot.
python
%matplotlib inline import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6])
Example
This example shows how to use %matplotlib inline to display a simple line plot inside a Jupyter notebook.
python
%matplotlib inline import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4] y = [0, 1, 4, 9, 16] plt.plot(x, y) plt.title('Simple Inline Plot') plt.xlabel('x axis') plt.ylabel('y axis') plt.grid(True) plt.show()
Output
A line plot with points (0,0), (1,1), (2,4), (3,9), (4,16) displayed inline below the code cell.
Common Pitfalls
Some common mistakes when trying to display matplotlib plots inline include:
- Not running
%matplotlib inlinein the notebook, so plots open in a separate window or do not display. - Using
plt.show()unnecessarily in some environments, though it is harmless. - Running the code outside Jupyter notebooks where
%matplotlib inlineis not recognized.
Always ensure you run %matplotlib inline at the start of your notebook.
python
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) # Without %matplotlib inline, plot may not display inline in Jupyter # Correct way: %matplotlib inline import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6])
Quick Reference
Summary tips for displaying matplotlib plots inline:
- Use
%matplotlib inlineat the start of your Jupyter notebook. - Import matplotlib.pyplot as
plt. - Create plots with
plt.plot()or other plotting functions. - Call
plt.show()if you want, but it is optional in Jupyter with inline mode.
Key Takeaways
Use %matplotlib inline at the start of Jupyter notebooks to display plots inside the notebook.
Import matplotlib.pyplot as plt to access plotting functions.
Plots will automatically appear below code cells without needing plt.show() in inline mode.
Without %matplotlib inline, plots may open in separate windows or not display in notebooks.
This method works only in Jupyter notebook environments, not in plain Python scripts.