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.
The shortcut
Before writing code, say the question aloud and the chart names itself. "Over time" → line. "Compare groups" → bar. "Together" → scatter. "Spread" → histogram. Then run the checklist: title, both axis labels, units.
Say the question
"How did copies change across the four days?" Over time, so a line.
The trap is a line chart for categories. A line from Chennai to Delhi to Pune suggests a trend between cities that does not exist. Separate groups get bars.
Drills
Answer fast — trust the rule.
Which chart fits "how do the three branches compare on revenue"?
In fig, ax = plt.subplots(), what is ax?
How many Axes does plt.subplots(2, 3) create?
Which chart best answers "do pricier books sell fewer copies"?
Remember
- Pick the chart by the question: time → line, groups → bar, together → scatter, spread → histogram.
- The Figure is the image; draw on an Axes from
plt.subplots(). - Every chart needs a title, both axis labels and units.
