W3docs

Matplotlib Intro

Learn what Matplotlib is, how it works, and how to create your first plots in Python with clear examples covering line charts, labels, and subplots.

Matplotlib is the most widely used data visualization library in Python. This chapter explains what Matplotlib is, how its core architecture works, and how to produce your first plots — from a minimal line chart to a labelled, multi-panel figure. Later chapters in this section go deeper on each plot type.

What is Matplotlib?

Matplotlib is an open-source Python library for creating static, animated, and interactive visualizations. John D. Hunter released the first version in 2003, initially to replicate MATLAB's plotting commands inside Python. Today it underlies many higher-level visualization tools (Seaborn, Pandas .plot(), SciPy) and is the de-facto standard for publication-quality figures in science and engineering.

Why use Matplotlib?

  • Broad plot types — line, scatter, bar, histogram, pie, box, violin, heatmap, contour, 3-D surfaces, and more.
  • Fine-grained control — every element of a figure (axes, tick marks, fonts, colors, legends) is reachable and configurable.
  • Multiple output formats — PNG, PDF, SVG, EPS, and interactive HTML (via the widget backend).
  • Ecosystem integration — works with NumPy arrays, Pandas DataFrames, and SciPy directly.
  • Free and open-source — BSD license, active community, extensive documentation.

When should you choose Matplotlib?

Use Matplotlib when you need precise, publication-ready control over every visual element, or when you are building on a system that requires a well-supported, stable library. For quick exploratory plots on DataFrames, Pandas' built-in .plot() (which calls Matplotlib underneath) is often faster to type. For statistical plots with a higher-level API, Seaborn is a popular complement that still lets you drop back to Matplotlib for fine-tuning.

How Matplotlib Is Structured

Understanding Matplotlib's two-layer architecture saves a lot of confusion later.

The Figure and Axes objects

Every Matplotlib visualization lives inside a Figure. A Figure is the top-level container — think of it as the canvas. Inside a Figure you place one or more Axes objects. An Axes is the actual plotting area that contains the x-axis, y-axis, tick marks, gridlines, and the data.

Figure
└── Axes (one or more)
    ├── x-axis (XAxis)
    ├── y-axis (YAxis)
    ├── Title
    ├── Lines / Patches / Collections (the plotted data)
    └── Legend

Pyplot vs. object-oriented style

Matplotlib exposes two interfaces:

pyplot style — a set of functions in matplotlib.pyplot that automatically manage the current Figure and Axes. This mirrors MATLAB's workflow and is convenient for quick, one-off scripts.

Object-oriented (OO) style — you create Figure and Axes objects explicitly and call methods on them. This is preferred in production code, functions, and any script that creates more than one figure, because it makes clear exactly which axes each command targets.

Both styles produce identical output. The examples in this chapter use the OO style and note where pyplot shorthand differs.

Installing Matplotlib

Matplotlib is not part of Python's standard library. Install it with pip:

pip install matplotlib

If you use Anaconda or Miniconda, Matplotlib is included by default. To install it explicitly:

conda install matplotlib

Verify the installation:

python -c "import matplotlib; print(matplotlib.__version__)"

Importing Matplotlib

The standard import convention throughout the Python community is:

Standard Matplotlib import

import matplotlib.pyplot as plt

The alias plt is universal — every tutorial, textbook, and Stack Overflow answer uses it, so stick with it.

If you also need NumPy (common for generating data):

Import Matplotlib and NumPy together

import numpy as np
import matplotlib.pyplot as plt

Your First Plot

The simplest possible Matplotlib script: two lists of numbers, one call to plot(), one call to show().

Minimal line chart

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

fig, ax = plt.subplots()   # create Figure and Axes
ax.plot(x, y)              # draw a line through the points
plt.show()                 # open the display window (scripts only)

plt.subplots() returns a tuple (fig, ax). Most code in this section uses this pattern because it makes it explicit which Axes you are drawing on.

In Jupyter notebooks plt.show() is optional — plots render inline automatically when a cell finishes executing.

In standalone scripts plt.show() opens a window and pauses execution until the window is closed. Without it, the script exits before the window appears.

Adding Labels and a Title

Axis labels and a title turn a raw chart into a readable figure.

Line chart with labels and title

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel('x')
ax.set_ylabel('x squared')
ax.set_title('Square Numbers')
plt.show()
MethodWhat it sets
ax.set_xlabel('text')Label on the horizontal axis
ax.set_ylabel('text')Label on the vertical axis
ax.set_title('text')Title above the plot

See the Matplotlib Labels chapter for font size, weight, and placement options.

Customizing Line Style and Color

ax.plot() accepts keyword arguments that control the visual appearance of the line.

Dashed red line

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

fig, ax = plt.subplots()
ax.plot(x, y, color='red', linestyle='--', linewidth=2)
ax.set_title('Dashed Red Line')
plt.show()

Common linestyle values: '-' (solid, default), '--' (dashed), ':' (dotted), '-.' (dash-dot).

Common named colors: 'blue', 'red', 'green', 'orange', 'purple', 'black'. Hex codes like '#1f77b4' also work.

See Matplotlib Line and Matplotlib Markers for a full list of styling options.

Plotting Multiple Lines and Adding a Legend

Call ax.plot() more than once to overlay multiple lines on the same Axes. Pass label= to each call, then call ax.legend() to render the legend box.

Two overlapping lines with a legend

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)

fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)', linestyle='--')
ax.set_xlabel('Angle (radians)')
ax.set_ylabel('Value')
ax.set_title('Sine and Cosine')
ax.legend()
plt.show()

np.linspace(0, 2 * np.pi, 100) creates 100 evenly spaced numbers from 0 to 2π — a convenient way to produce smooth curves.

Creating Subplots

plt.subplots(rows, cols) creates a grid of Axes inside a single Figure. You access each Axes by index.

2×2 grid of different chart types

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

axs[0, 0].plot(x, y)
axs[0, 0].set_title('Line')

axs[0, 1].scatter(x[::5], y[::5])  # every 5th point
axs[0, 1].set_title('Scatter')

axs[1, 0].bar(['A', 'B', 'C'], [3, 7, 5])
axs[1, 0].set_title('Bar')

axs[1, 1].hist(np.random.randn(500), bins=20)
axs[1, 1].set_title('Histogram')

fig.tight_layout()   # prevent overlapping labels
plt.show()

fig.tight_layout() automatically adjusts spacing between subplots so that titles and labels do not overlap. It is almost always a good idea to call it when using subplots.

See Matplotlib Subplot for more on grid layouts, shared axes, and GridSpec.

Saving Figures

To save a figure to a file instead of displaying it interactively, call fig.savefig() before plt.show().

Save a figure as PNG and PDF

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Saved Figure')

fig.savefig('my_plot.png', dpi=150)   # raster: PNG at 150 DPI
fig.savefig('my_plot.pdf')            # vector: PDF (no DPI needed)
plt.show()

The dpi (dots per inch) argument controls resolution for raster formats. dpi=150 is a good balance between file size and print quality; dpi=300 is standard for journal figures.

Supported formats include PNG, PDF, SVG, EPS, and TIFF. Matplotlib detects the format from the file extension automatically.

What's Next

This chapter introduced Matplotlib's core concepts. The rest of the Python Matplotlib section covers each topic in depth:

Was this page helpful?