Line plots with plot()

Matplotlib · Essentials · 10 min

Line plots are the default way to show trends over time or any ordered x, and plot is the most used function in the library.

ax.plot(x, y) connects the points (x[i], y[i]) with straight segments. x and y can be lists, NumPy arrays or pandas Series of the same length. If you pass only one sequence, it is used as y and x becomes 0, 1, 2, ....

Call plot several times on the same Axes to overlay lines; each new line takes the next color from the property cycle (blue, orange, green, ...). Style each line with keyword arguments:

  • color="tab:red" or a hex string like "#11557C".
  • linestyle="--" (dashed), ":" (dotted), "-.".
  • marker="o" to draw a symbol at each point, markersize=4.
  • linewidth=2, alpha=0.6 for transparency.
  • label="train" so a legend can name the line later.

A compact format string such as "ro--" (red, circle markers, dashed) is also accepted as the third positional argument; it is handy in quick exploration, but keyword arguments read better in code others maintain.

Smooth-looking curves are just many points: x = np.linspace(0, 10, 200) then ax.plot(x, np.sin(x)). With too few points you see the straight segments.

plot returns a list of Line2D objects. Keep a reference (line, = ax.plot(...)) if you want to change the line later, for example in an animation.

Line plots assume the x values are ordered. If they are not, the line zigzags back and forth: sort by x first, or use scatter for unordered points.

Example

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import to_hex

x = np.linspace(0, 2 * np.pi, 100)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="sin")
ax.plot(x, np.cos(x), linestyle="--", color="tab:red", label="cos")
line, = ax.plot(x[::10], np.sin(x[::10]), "ko", markersize=3)

print(len(ax.lines))                  # 3
print(line.get_marker())              # o
print(to_hex(ax.lines[0].get_color()))  # #1f77b4 (first cycle color)
fig.savefig("lines.png")

Remember

  • ax.plot(x, y) connects points in order; one sequence means y vs index
  • Repeated calls overlay lines with the next cycle color
  • Style with color, linestyle, marker, linewidth, label

Watch out for

  • Plotting unsorted x values with a line, which produces a zigzag mess.

Check yourself

  1. You call `ax.plot([5, 3, 8])` with a single list. What are the x values?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html