Sub topic 9
Working with the returned Axes and saving figures
This chapter assumes you can call df.plot with kind, and that you know what a pandas index is. You also need matplotlib installed. Here you will learn what plot returns, how to use it for finer control, and how to write a chart to a file.
What plot returns
DataFrame.plot draws on a matplotlib Axes, the object that holds one set of x and y axes, and returns it. An Axes sits inside a Figure, the whole canvas. Most pandas charts are one Figure with one Axes.
Keep the return value in a variable, and you can customize the chart after the call.
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.bar(
title="Monthly sales",
color="steelblue",
figsize=(6, 4),
rot=0,
)
ax.set_xlabel("Month")
ax.set_ylabel("Units sold")
ax.figure.savefig("sales.png", dpi=150, bbox_inches="tight")Any matplotlib Axes method works on ax. The three calls above set labels and save the file. The ax.figure attribute gives the parent Figure, which owns savefig.
Saving a figure
savefig picks the file format from the extension, such as .png, .pdf or .svg. Two arguments matter most:
dpisets the resolution in dots per inch. Use 150 to 300 for reports.bbox_inches="tight"trims empty margins and stops long labels from being cut off.
Drawing several plots on one Axes
The ax argument tells plot to draw on an existing Axes instead of making a new one. Use it to combine chart types, such as bars for one column and a line for another.
fig, ax = plt.subplots(figsize=(6, 4))
indexed = df.set_index("month")
indexed["sales"].plot.bar(ax=ax, color="lightgray", rot=0)
indexed["costs"].plot(ax=ax, color="crimson", marker="o")
ax.set_title("Sales and costs")
ax.set_ylabel("Units")
fig.savefig("sales_costs.png", dpi=150, bbox_inches="tight")
plt.show()Here plt.subplots creates the Figure and Axes first, and both plot calls share that Axes. This pattern also lets you place several pandas charts in one grid of panels, passing a different Axes to each call.
Axes when you use subplots=True
With subplots=True, plot returns a NumPy array of Axes, one per column, instead of a single Axes. Index into the array to customize each panel.
axes = df.set_index("month").plot(subplots=True, layout=(1, 2), figsize=(8, 3), legend=False)
axes[0, 0].set_ylabel("Units")
axes[0, 1].set_title("Costs, own scale")
axes[0, 0].figure.savefig("panels.png", bbox_inches="tight")The array has the shape of layout, so a (1, 2) layout needs two indexes. Without layout, the array is one-dimensional.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Saved image is blank | `savefig` called after `plt.show()` | Save first, then show |
| Labels cut off in the file | Default margins | Add `bbox_inches="tight"` |
| `AttributeError: 'numpy.ndarray' object has no attribute 'set_title'` | `subplots=True` returned an array | Index into the array |
| Second plot opens a new figure | `ax` not passed | Pass `ax=ax` to each call |
Exercise
You run ax = df.set_index("month")["sales"].plot.line() and then want to save it as a high-resolution PNG named line.png with no clipped labels. Which line do you write, and why use ax.figure?
Show answer
ax.figure.savefig("line.png", dpi=300, bbox_inches="tight"). The Axes only draws the chart. The Figure that contains it owns savefig, and ax.figure gives you that Figure. The dpi value raises resolution, and bbox_inches="tight" prevents clipping.
Exercise
You call df.set_index("month").plot(subplots=True) and then run ax.set_title("Costs") on the result, but get an AttributeError. What happened, and how do you fix it?
Show answer
With subplots=True, plot returns an array of Axes, not one Axes. Index into it, for example axes[1].set_title("Costs"), or axes[0, 1] if you passed a two-dimensional layout.