First Plots with Matplotlib
A table of per-day totals is accurate, but a picture shows the pattern in a second: a rising line, one tall bar, a cloud of points drifting upward. Matplotlib is the plotting library underneath most Python charts, including the ones pandas draws for you.
The rule
Pick the chart by the question; draw on an Axes, label it, show it.
Match the question to the chart:
| Question | Chart | Matplotlib call |
|---|---|---|
| How does it change over time? | line | ax.plot(x, y) |
| How do categories compare? | bar | ax.bar(labels, heights) |
| Do two numbers move together? | scatter | ax.scatter(x, y) |
| How are values spread out? | histogram | ax.hist(values) |
Matplotlib has two layers. The Figure is the whole image; an Axes is one plotting area inside it, with its own x and y axis. plt.subplots() makes both:
import matplotlib.pyplot as plt
per_branch = sales.groupby("branch")["copies"].sum()
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(per_branch.index, per_branch.values, color="teal")
ax.set_title("Copies sold per branch")
ax.set_xlabel("Branch")
ax.set_ylabel("Copies")
plt.show()Several charts side by side come from asking for a grid of Axes:
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4))
per_day = sales.groupby("date")["copies"].sum()
left.plot(per_day.index, per_day.values, marker="o")
left.set_title("Copies per day")
right.scatter(sales["price"], sales["copies"])
right.set_title("Price vs copies")
fig.tight_layout()subplots(1, 2) means 1 row and 2 columns of Axes. tight_layout() stops titles and labels from overlapping.
pandas has a shortcut that calls Matplotlib for you: per_branch.plot(kind="bar") draws the same bar chart and returns the Axes, so you can still add labels.