Sub topic 3
Working with the Returned Axes and Saving Figures
Assume you know basic pandas selection and groupby, and that pandas and Matplotlib are installed. The plot method returns a Matplotlib Axes object. Use it to add labels, change limits, or save the figure.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 135, 150, 170],
"costs": [80, 90, 95, 110],
})
ax = df.set_index("month")["sales"].plot(
marker="o",
color="steelblue",
title="Monthly sales",
figsize=(6, 4),
)
ax.set_xlabel("Month")
ax.set_ylabel("Units sold")
ax.figure.savefig("sales.png", dpi=150, bbox_inches="tight")
plt.show()The Axes object controls one chart. ax.figure refers to its containing figure. Saving before plt.show() avoids problems in some environments.
One Panel per Column
Use subplots=True when columns need separate scales or comparisons.
axes = df.set_index("month").plot(
subplots=True,
layout=(1, 2),
figsize=(8, 3),
sharex=False,
legend=False,
)
plt.tight_layout()
plt.show()The result is an array of Axes objects, one for each numeric column.
Summarize First, Then Plot
Raw rows are often too detailed for a useful chart. Aggregate them first.
orders = pd.DataFrame({
"region": ["north", "south", "north", "east", "south", "north"],
"amount": [10, 20, 15, 5, 30, 25],
})
orders.groupby("region")["amount"].sum().sort_values().plot.barh()
orders["region"].value_counts().plot.bar(rot=0)For two categorical dimensions, use pivot_table:
table = orders.pivot_table(
values="amount", index="region", aggfunc="sum"
)
table.plot.bar()
plt.show()Time Series and Common Errors
Convert dates to datetime values and make them the index.
df["date"] = pd.to_datetime(["2026-01-01", "2026-02-01", "2026-03-01", "2026-04-01"])
df.set_index("date")["sales"].plot(marker="o")
plt.show()| Problem | Likely cause | Remedy |
|---|---|---|
| No numeric data | Selected only text columns | Select numeric columns |
| Gaps or warnings | Missing values | Inspect or fill missing values |
| Unreadable labels | Too many categories | Aggregate, rotate labels, or use horizontal bars |
Exercise
What does plot(subplots=True) return?
Show answer
An array of Matplotlib Axes objects, with one panel for each plotted column.