W3docs

Matplotlib Get Started

Learn how to install Matplotlib, import pyplot, and create your first line plot with labels, colors, and customization options.

This page covers everything you need to begin using Matplotlib: how to install it, how to import it, how the library is structured, and how to create and customize your first plot. By the end you will have a working script that produces a fully labeled line chart.

Installing Matplotlib

Matplotlib is not part of the Python standard library, so you must install it before you can import it. Use pip, Python's package manager:

pip install matplotlib

If you are working inside a virtual environment (recommended), activate it first and then run the command above. To confirm that the installation succeeded and check the version:

python -m pip show matplotlib

You should see output like:

Name: matplotlib
Version: 3.9.x
...

Matplotlib requires Python 3.9 or newer as of the 3.9 release series.

Importing Matplotlib

Matplotlib is organised into several sub-packages. For day-to-day plotting you only need the pyplot module, which is conventionally imported under the alias plt:

import matplotlib.pyplot as plt

The alias plt is the universal convention in the Python community. Using it makes your code consistent with tutorials, documentation, and code you find on the web.

If you also need numerical arrays (common when generating data to plot), import NumPy at the same time:

import matplotlib.pyplot as plt
import numpy as np

How Matplotlib Is Structured

Understanding the two-layer structure of Matplotlib prevents a lot of confusion:

  • Figure — the top-level container. Think of it as the canvas or the window. A Figure can hold one or more Axes.
  • Axes — a single plot area with its own x-axis, y-axis, title, and data. The word "Axes" does not mean the axis lines alone; it is the whole plot region.

Matplotlib exposes two interfaces for working with these objects:

InterfaceWhen to use
pyplot (state-machine)Quick, interactive scripts and notebooks
Object-Oriented (OO)Multi-panel figures, reusable functions, production code

The pyplot interface manages the current Figure and Axes for you. The OO interface gives you explicit handles so you can control every object precisely. Both produce identical output; the difference is code organisation.

Creating Your First Plot

The plt.plot() function draws a line through a sequence of (x, y) pairs. Pass two equal-length lists — one for x-values and one for y-values:

import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.show()

plt.show() sends the figure to the screen. In a terminal script, execution pauses until you close the plot window. In a Jupyter notebook, the plot appears inline and plt.show() is optional.

Adding Labels and a Title

A plot without labels is hard to interpret. Add axis labels and a title with three one-line calls:

import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y = x²')
plt.title('Square Numbers')
plt.show()
  • plt.xlabel() — label for the horizontal axis.
  • plt.ylabel() — label for the vertical axis.
  • plt.title() — title displayed above the plot.

Customizing Line Color and Style

Pass keyword arguments to plt.plot() to change the appearance of the line:

import matplotlib.pyplot as plt

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

plt.plot(x, y, color='steelblue', linewidth=2, linestyle='--')
plt.xlabel('x')
plt.ylabel('y = x²')
plt.title('Square Numbers')
plt.show()

Common options:

ParameterExample valuesEffect
color'red', 'steelblue', '#2ca02c'Line color
linewidth1, 2, 3Line thickness in points
linestyle'-', '--', ':', '-.'Solid, dashed, dotted, dash-dot

You can also use a shorthand format string as the third positional argument. 'r--' means red dashed, 'bs' means blue squares, 'g^' means green triangles:

plt.plot(x, y, 'r--')

Setting Axis Limits

By default Matplotlib chooses axis limits that fit the data. You can override them:

import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.xlim(0, 5)
plt.ylim(0, 20)
plt.show()

plt.xlim(min, max) and plt.ylim(min, max) set the visible range of each axis. This is useful when you want to highlight a specific region or keep the axes consistent across multiple plots.

Plotting Multiple Lines

Call plt.plot() more than once before plt.show() to overlay several lines on the same Axes. Add a label argument to each call, then call plt.legend() to display the key:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y_sq = [1, 4, 9, 16, 25]
y_cb = [1, 8, 27, 64, 125]

plt.plot(x, y_sq, color='steelblue', label='x²')
plt.plot(x, y_cb, color='tomato', label='x³')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Comparing Growth')
plt.legend()
plt.show()

plt.legend() reads the label string from each plot() call and builds the legend automatically. Place it before plt.show().

The Object-Oriented Interface

For anything beyond a single simple chart, the OO interface is clearer and easier to maintain. Create a Figure and one or more Axes with plt.subplots(), then call methods directly on the ax object:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y_sq = [1, 4, 9, 16, 25]
y_cb = [1, 8, 27, 64, 125]

fig, ax = plt.subplots()

ax.plot(x, y_sq, color='steelblue', label='x²')
ax.plot(x, y_cb, color='tomato', label='x³')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Comparing Growth')
ax.legend()
ax.grid(True)

plt.show()

The OO method names mirror the pyplot functions with a set_ prefix: plt.xlabel() becomes ax.set_xlabel(), plt.title() becomes ax.set_title(), and so on. The explicit ax handle makes it unambiguous which plot you are modifying — essential when a Figure holds several subplots.

Saving a Plot to a File

Call plt.savefig() instead of (or in addition to) plt.show() to write the figure to disk:

import matplotlib.pyplot as plt

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

plt.plot(x, y, color='steelblue', linewidth=2)
plt.xlabel('x')
plt.ylabel('y = x²')
plt.title('Square Numbers')
plt.savefig('square_numbers.png', dpi=150, bbox_inches='tight')

Matplotlib infers the file format from the extension. Common formats: .png, .pdf, .svg, .jpg. The dpi argument controls resolution (150–300 dpi is typical for reports). bbox_inches='tight' trims whitespace from the edges.

Common Gotchas

Call plt.show() only once. Calling it multiple times in a script can produce blank figures because Matplotlib clears the current figure after displaying it.

Order matters with pyplot. Customisation calls (plt.xlabel(), plt.title(), etc.) must come before plt.show().

Reusing a figure. If you build a plot in a loop and forget to clear it, data from previous iterations accumulates. Call plt.clf() (clear figure) or plt.close() between iterations, or create a new fig, ax = plt.subplots() each time.

Non-interactive backends. On servers without a display (CI, Docker containers), plt.show() may raise an error. Set the backend before importing pyplot:

import matplotlib
matplotlib.use('Agg')  # non-interactive PNG backend
import matplotlib.pyplot as plt

Next Steps

Now that you can produce a basic plot, explore the dedicated chapters:

Was this page helpful?