Charts with Matplotlib
Why this matters
A chart is often the only part of an analysis anyone else sees. A good one makes a pattern obvious in a second; a careless one hides it, or invents a pattern that isn't there. In the AI phases you'll chart loss curves, compare model scores and look at data before you train on it, so being quick and careful with Matplotlib pays off in every phase after this one.
- Make a figure and axes, and draw line, bar, scatter, histogram and box plots on them
- Label every chart so a reader knows what they're looking at
- Choose a log scale, a zero baseline and small multiples on purpose
- Spot the unfinished-period trap before it fools you or your reader
A figure and its axes
Matplotlib is Python's standard charting library. Two objects do the work:
- The figure is the whole picture, like a sheet of paper.
- An axes is one chart on that sheet: the plotting area, its two axis lines, its labels.
plt.subplots() makes both at once. You then draw on the axes and label it:
import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] orders = [405, 416, 579, 735, 846, 848] fig, ax = plt.subplots(figsize=(6, 3.5)) ax.plot(months, orders, marker="o") ax.set_title("Trail-shoe orders, first half of 2024") ax.set_ylabel("orders") ax.set_ylim(bottom=0)
In the academy, every open figure appears under the output when the code finishes. On your own computer you'd add plt.show() to open a window, or fig.savefig("orders.png") to save a file.
The habit to build from day one: every chart gets a title and labeled axes. A chart without them makes the reader guess what they're looking at.
Five charts for five questions
Pick the chart from the question you're asking:
| Question | Chart | Matplotlib |
|---|---|---|
| How does it change over time? | line | ax.plot(x, y) |
| How do categories compare? | bar | ax.bar(names, values) |
| Do two numbers move together? | scatter | ax.scatter(x, y) |
| What values are common? | histogram | ax.hist(values, bins=20) |
| How do groups' spreads compare? | box plot | ax.boxplot(groups) |
Here are three of them on the practice shop's catalog:
import matplotlib.pyplot as plt import pandas as pd catalog = pd.read_csv("https://api.gradient.test/v1/datasets/catalog.csv") fig, axes = plt.subplots(1, 3, figsize=(12, 3.5)) by_category = catalog.groupby("category")["units_q2"].sum().sort_values() axes[0].barh(by_category.index, by_category.values) axes[0].set_title("Units sold in Q2") axes[1].scatter(catalog["price"], catalog["units_q2"], alpha=0.7) axes[1].set_title("Price against units sold") axes[1].set_xlabel("price ($)") axes[1].set_ylabel("units in Q2") axes[2].hist(catalog["price"], bins=12) axes[2].set_title("How prices are spread") axes[2].set_xlabel("price ($)") fig.tight_layout()
plt.subplots(1, 3) gives one row of three axes, in an array you index like a list. barh draws the bars sideways, which leaves room for long category names. tight_layout() nudges the three charts apart so their labels don't overlap.