Sub topic 14
Plotting backends and when to move beyond df.plot
This chapter assumes you can build a DataFrame, call df.plot, and use the returned matplotlib Axes from earlier chapters. It covers what happens behind plot, how to switch the engine, and when to stop using df.plot.
What a backend is
df.plot does not draw anything itself. It prepares the data and hands it to a plotting backend, which creates the figure. The default backend is matplotlib. That is why plot returns an Axes and why plt.show() and savefig work.
Switching the backend
Set the backend for one call with the backend argument. Set it for the whole session with a pandas option. Both need the other library installed. This example uses plotly.
import pandas as pd
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 135, 150, 170],
})
# One call only
fig = df.plot(x="month", y="sales", backend="plotly")
fig.show()
# Every later call in this session
pd.options.plotting.backend = "plotly"The return value changes with the backend. With matplotlib you get an Axes. With plotly you get a plotly Figure. Code such as ax.set_xlabel(...) fails on a plotly figure, so keep backend-specific customization next to the call that creates the chart.
Other backends exist as packages, for example hvplot for holoviews and bokeh. Check that a package supports the pandas backend interface before relying on it. Not every backend supports every kind, and some arguments, such as rot or marker, are matplotlib-specific.
Where df.plot stops being enough
df.plot is a thin layer for quick charts. It works well for one chart from one DataFrame. Move to matplotlib directly when you need any of these:
- Different chart types on one Axes, such as bars with a line on a second y axis.
- Annotations, arrows, or shaded regions placed at data coordinates.
- Precise control over a figure with a custom grid of unequal panels.
- Animation, or a chart that updates in place.
You do not have to abandon df.plot completely. A common pattern is to create the figure and Axes yourself, then pass the Axes to plot through the ax argument:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 135, 150, 170],
"costs": [80, 90, 95, 110],
})
data = df.set_index("month")
fig, ax = plt.subplots(figsize=(6, 4))
data["sales"].plot.bar(ax=ax, color="lightgray", rot=0)
ax2 = ax.twinx()
data["costs"].plot(ax=ax2, color="crimson", marker="o")
ax.set_ylabel("Sales")
ax2.set_ylabel("Costs")
ax.annotate("Peak", xy=(3, 170), xytext=(2, 175),
arrowprops={"arrowstyle": "->"})
fig.tight_layout()
plt.show()Here pandas draws both series, and matplotlib supplies the second y axis and the annotation. The sales bars and the costs line share one x axis because both series use the same month index.
Choosing a tool
| Need | Suggested tool |
|---|---|
| Quick look at your data | `df.plot` |
| A chart to save for a report | `df.plot` plus the returned Axes |
| Combined or annotated charts | matplotlib with `ax=` |
| Hover tooltips and zoom in a notebook | A plotly or bokeh backend |
| Statistical charts with many categories | A library such as seaborn |
Start with df.plot. Move to a lower-level tool when you find yourself fighting the arguments.
Exercise
You set pd.options.plotting.backend = "plotly" and your existing line ax.set_ylabel("Units") now raises an error. Why does it fail, and what are two ways to fix it?
Show answer
With the plotly backend, df.plot returns a plotly Figure, not a matplotlib Axes, so set_ylabel does not exist. Fix it by resetting the option to "matplotlib" (or passing backend="matplotlib" to that call), or by using the plotly API on the figure, for example fig.update_yaxes(title_text="Units").