Line plots

Several series, markers, and linestyles.

Line plots connect samples in order. Several series on one Axes need a legend. Markers help when the series is short.

Goal

Overlay two series, pick a linestyle, and label them.

Two series

months = ["Jan", "Feb", "Mar", "Apr"]
nairobi = [50, 40, 80, 150]
kisumu = [70, 80, 120, 180]
fig, ax = plt.subplots()
ax.plot(months, nairobi, marker="o", label="Nairobi")
ax.plot(months, kisumu, marker="s", label="Kisumu")
ax.set_ylabel("mm")
ax.set_title("Rainfall")
ax.legend()
plt.show()

Linestyles

x = np.linspace(0, 4, 40)
fig, ax = plt.subplots()
ax.plot(x, x, linestyle="-", label="solid")
ax.plot(x, x + 1, linestyle="--", label="dashed")
ax.plot(x, x + 2, linestyle=":", label="dotted")
ax.legend()
ax.set_title("Linestyles")
plt.show()

A fmt string

x = np.linspace(0, 2 * np.pi, 20)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), "o--", label="sin")
ax.legend()
ax.set_title("marker + dashed")
plt.show()

"o--" is marker o and a dashed line. The Color chapter covers the rest of the fmt mini-language.

Tip

If the x values are not sorted, plot still connects them in array order — that draws scribbles. Sort, or use scatter.