Matplotlib - Jupyter Notebook
Matplotlib - Using with Jupyter Notebooks
Section titled “Matplotlib - Using with Jupyter Notebooks”Jupyter Notebook (and related tools like JupyterLab, Google Colab, VS Code Notebooks) is an interactive computing environment that allows you to create and share documents containing live code, equations, visualizations, and narrative text. It’s extremely popular in data science and scientific computing.
Matplotlib integrates seamlessly with Jupyter, allowing you to embed plots directly within your notebooks, making it ideal for exploratory data analysis and sharing results.
Starting Jupyter
Section titled “Starting Jupyter”If you installed Python via Anaconda, you can usually launch Jupyter Notebook or JupyterLab from the Anaconda Navigator GUI.
Alternatively, you can start it from your terminal or command prompt (ensure your desired conda environment is active, if using environments):
# To start Jupyter Notebookjupyter notebook
# To start JupyterLab (a more modern interface)jupyter labThis will typically open a new tab in your web browser showing the Jupyter file browser, usually at an address like http://localhost:8888/....
From the file browser view, you can navigate directories and create new notebooks. Click on the “New” button (or equivalent, depending on the Jupyter version/interface) and select the desired kernel (e.g., “Python 3”) to create a new .ipynb notebook file.
Plotting Inline
Section titled “Plotting Inline”The key feature when using Matplotlib in Jupyter is the ability to display plots directly below the code cell that generated them. This is often enabled by default, but the standard way to ensure this behavior is using the %matplotlib inline magic command.
import matplotlib.pyplot as pltimport numpy as np
# Magic command to display plots inline%matplotlib inline
# --- Example Plot ---x = np.linspace(0, 5, 50)y = x**2
plt.figure()plt.plot(x, y)plt.title('Square Function Plot')plt.xlabel('x')plt.ylabel('x^2')plt.grid(True)
# No plt.show() is needed here.# The plot appears below the cell upon execution.When you run this cell (e.g., by pressing Shift+Enter), the plot image will be rendered and embedded in the notebook’s output area.
Interactive Backends (Optional)
Section titled “Interactive Backends (Optional)”While %matplotlib inline produces static images, Jupyter also supports interactive Matplotlib backends. These allow panning, zooming, and sometimes other interactions directly within the notebook output.
Common interactive backends include:
%matplotlib notebook: Provides basic interactivity within the output cell (may requireipympllibrary:pip install ipympl).%matplotlib widget: A more modern and feature-rich interactive backend, also requiringipympl.%matplotlib qt: Opens plots in separate Qt windows (requires a Qt binding like PyQt5 or PySide6).%matplotlib tk: Opens plots in separate Tkinter windows.
To use an interactive backend, replace %matplotlib inline with the desired magic command at the beginning of your notebook (or session).
# Example using the 'widget' backend (requires ipympl)# pip install ipympl# jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter-matplotlib
import matplotlib.pyplot as pltimport numpy as np
%matplotlib widget
x = np.linspace(0, 2*np.pi, 100)y = np.sin(x)
fig, ax = plt.subplots()ax.plot(x, y)ax.set_title('Interactive Sine Plot (widget)')ax.grid(True)
# With interactive backends, plt.show() might sometimes be needed# to initially render or update the plot, depending on usage.# plt.show() # Often not strictly required for initial display in widget.Choosing between inline (static) and interactive backends depends on your needs. Inline is simple and good for static reports, while interactive backends are better for exploring data dynamically.