Sub topic 9
Working with the returned Axes and saving figures
DataFrame.plot draws a chart in one call, but it also returns an object you can keep working with. This chapter shows what that object is, how to use it to customize a chart, how to aim a chart at an axes you already created, and how to save the result to a file.
This chapter assumes you can create a DataFrame, select columns, and call df.plot with kind or the df.plot.<kind> accessors. Matplotlib must be installed.
What plot returns
Every plot call returns a matplotlib Axes object. An Axes is the rectangular drawing area that holds the plotted data, the tick marks, the axis labels, the title and the legend. The Axes belongs to a Figure, which is the whole canvas, and which can hold one or several Axes.
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").plot(marker="o")
print(type(ax))
print(type(ax.figure))
plt.show()The two print calls show matplotlib.axes._axes.Axes and matplotlib.figure.Figure. The figure attribute of an Axes points back to its parent figure.
The return value depends on the call:
| Call | Return value |
|---|---|
| `df.plot(...)` with one panel | One `Axes` |
| `df.plot(subplots=True)` | A NumPy array of `Axes` |
| `df.plot.hist(...)`, `df.plot.box()` | One `Axes` |
| `df["col"].plot(...)` (a Series) | One `Axes` |
Subplots are covered in their own chapter. Here the focus is the single-Axes case.
Customizing a chart with the Axes
Many plot arguments exist (title, figsize, color), but some settings are only available on the Axes. Axis labels, axis limits, tick formatting, grid lines, annotations and reference lines are the common ones.
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.set_ylim(0, 200)
ax.grid(axis="y", linestyle=":", alpha=0.6)
ax.axhline(150, color="crimson", linestyle="--", label="Target")
ax.legend()
plt.show()Each method does one thing:
set_xlabelandset_ylabelset the axis labels.set_ylim(0, 200)fixes the visible y range. Without it, matplotlib picks a range from the data.grid(axis="y", ...)draws horizontal grid lines only.axhlinedraws a horizontal line across the whole Axes. Itslabelmakes it appear in the legend. Useaxvlinefor a vertical line.legend()rebuilds the legend so it includes the new line.
Annotations work the same way:
ax = df.set_index("month")["sales"].plot(marker="o", figsize=(6, 4))
peak = df["sales"].idxmax()
ax.annotate(
"Best month",
xy=(peak, df["sales"].max()),
xytext=(peak - 1, df["sales"].max() + 5),
arrowprops={"arrowstyle": "->"},
)
plt.show()The xy point is in data coordinates. Here the x value is the integer position of the row, which works because a line plot over a string index places categories at positions 0, 1, 2 and so on.
Setters you can also pass as arguments
Some Axes settings have a matching plot argument, so you can choose either style.
| Axes method | Equivalent `plot` argument |
|---|---|
| `ax.set_title("T")` | `title="T"` |
| `ax.set_xlim(a, b)` | `xlim=(a, b)` |
| `ax.set_ylim(a, b)` | `ylim=(a, b)` |
| `ax.grid(True)` | `grid=True` |
| `ax.set_xlabel("X")` | `xlabel="X"` (pandas 1.1 and later) |
| `ax.set_ylabel("Y")` | `ylabel="Y"` (pandas 1.1 and later) |
Passing arguments keeps the code short. Use the Axes methods when you need options the arguments do not expose, such as fontsize on a label or linestyle on a grid.
Drawing on an existing Axes with the ax argument
The ax argument tells plot where to draw. If you leave it out, pandas uses the current Axes from pyplot, or creates one. Passing ax gives you control over placement and lets you layer several plots on one Axes.
fig, ax = plt.subplots(figsize=(6, 4))
data = df.set_index("month")
data["sales"].plot(ax=ax, label="Sales", marker="o")
data["costs"].plot(ax=ax, label="Costs", marker="s")
ax.set_title("Sales and costs")
ax.set_ylabel("Amount")
ax.legend()
plt.show()Here plt.subplots creates the Figure and Axes first. Both Series are then drawn onto the same Axes. The label argument sets the legend text for a Series, which otherwise uses the column name.
The same pattern places charts side by side in a figure you control:
fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.5))
data["sales"].plot.bar(ax=left, rot=0, title="Sales")
data["costs"].plot.bar(ax=right, rot=0, title="Costs", color="darkorange")
fig.tight_layout()
plt.show()When you pass ax, figsize in the plot call has no effect, because the figure already exists. Set the size in plt.subplots instead.
Secondary axes
When two columns have very different scales, secondary_y plots a column against a second y axis on the right.
scale = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"units": [120, 135, 150, 170],
"revenue": [12000, 14500, 16000, 19500],
}).set_index("month")
ax = scale["units"].plot(marker="o", label="Units", legend=True)
ax2 = scale["revenue"].plot(secondary_y=True, marker="s", color="darkorange",
label="Revenue", legend=True, ax=ax)
ax.set_ylabel("Units")
ax.right_ax.set_ylabel("Revenue")
plt.show()The second call returns the Axes for the first plot's twin, and pandas exposes the right-hand axis as ax.right_ax. Use secondary axes sparingly. Two scales on one chart can suggest a relationship that is not in the data.
Saving a figure
A chart is saved from its Figure, not from the Axes. You can reach the Figure through ax.figure, or call plt.savefig to save the current figure.
ax = df.set_index("month")["sales"].plot.bar(
title="Monthly sales", figsize=(6, 4), rot=0
)
ax.set_xlabel("Month")
ax.set_ylabel("Units sold")
ax.figure.savefig("sales.png", dpi=150, bbox_inches="tight")Three arguments matter most:
dpisets dots per inch. A 6 by 4 inch figure atdpi=150produces a 900 by 600 pixel image.bbox_inches="tight"crops the saved image to the content, so long labels are not cut off at the border.transparent=Trueleaves the background empty, which helps when placing the chart on a colored slide.
The file format comes from the extension. Use .png for web pages and documents, .svg or .pdf for vector output that stays sharp at any size, and .jpg only for photographs. You can also set it with format="svg".
Save before you show
In a script, call savefig before plt.show(). With many backends, show() closes the figure when its window is dismissed, and a later savefig then writes an empty image. In Jupyter, inline figures are usually safe to save afterward, but saving first is a habit that works everywhere.
Saving in a loop
A script that makes many charts should close each figure after saving. Matplotlib keeps every open figure in memory, and it warns once more than 20 are open.
regions = {
"north": [10, 15, 25],
"south": [20, 30, 10],
}
for name, values in regions.items():
ax = pd.Series(values, index=["a", "b", "c"]).plot.bar(title=name, rot=0)
ax.figure.savefig(f"{name}.png", dpi=120, bbox_inches="tight")
plt.close(ax.figure)Without plt.close, the second iteration would draw onto the same current Axes as the first, and the bars from both regions would pile up in one picture. Closing the figure makes the next plot call start on a fresh Axes. An alternative is to create a new figure and pass ax= explicitly each time.
How the pieces fit together
Common problems
- Settings seem to have no effect. You may be changing a different Axes than the one drawn on. Check that you used the returned
ax, or the sameaxyou passed in. - Saved image is blank.
savefigran aftershow()closed the figure. Move it beforeshow(). - Labels are clipped in the saved file. Add
bbox_inches="tight". - Charts from separate calls end up on top of each other. Both used the current Axes. Close the figure, or create separate Axes with
plt.subplots. - The legend is missing a line you added. Give the line a
label, then callax.legend()after adding it.
Exercise
You build a bar chart with ax = df.plot.bar() and then want to save it as a 300 dpi PNG with no clipped labels. Which line saves it, and why do you use ax.figure instead of calling a method on ax directly?
Show answer
ax.figure.savefig("chart.png", dpi=300, bbox_inches="tight"). The Axes only represents the drawing area. A file is written from the Figure, which holds the Axes and the whole canvas, so you reach it through ax.figure. The bbox_inches="tight" argument stops long labels from being cut off.
Exercise
A script loops over three regions and calls pd.Series(values).plot.bar() each time, then saves region.png. The second and third images contain bars from earlier regions. What causes this, and what two changes fix it?
Show answer
Each plot call without ax draws on the current Axes, so the bars accumulate. Fix it by calling plt.close(ax.figure) after each savefig, so the next call starts on a new Axes. Alternatively, create a new figure with fig, ax = plt.subplots() at the start of each iteration and pass ax=ax to plot.
Exercise
Using the data DataFrame from this chapter (indexed by month, with sales and costs), write code that draws both columns as lines on one Axes, adds a dashed horizontal line at 100 labeled "Budget", and shows a legend.
Show answer
fig, ax = plt.subplots() data["sales"].plot(ax=ax, label="Sales") data["costs"].plot(ax=ax, label="Costs") ax.axhline(100, linestyle="--", color="gray", label="Budget") ax.legend() plt.show()