Sub topic 14
Plotting backends and when to move beyond df.plot
This chapter assumes you can build a DataFrame, call df.plot with kind, x and y, and use the returned Axes from the earlier chapters. It covers three things. The first is what a plotting backend is and how to switch one. The second is what a backend changes and what it does not. The third is how to tell when df.plot is no longer the right tool.
What a backend is
df.plot does not draw anything itself. It validates its arguments, picks the data, and hands the work to a plotting backend. A backend is a Python module that exposes a plot(data, kind, **kwargs) function. The default backend is matplotlib, which is why df.plot returns a matplotlib Axes.
You can check the current backend through the pandas options:
import pandas as pd
print(pd.options.plotting.backend)This prints matplotlib unless you changed it.
Switching backends
There are three ways to choose a backend. They differ in scope.
| Scope | How | Use it when |
|---|---|---|
| One call | `df.plot(backend="plotly")` | You want a single interactive chart. |
| A block of code | `with pd.option_context("plotting.backend", "plotly"):` | You want to switch temporarily and restore the old value automatically. |
| The whole session | `pd.options.plotting.backend = "plotly"` | A notebook or script uses one library throughout. |
Here is the per-call form with Plotly. It assumes pip install plotly has been run:
import pandas as pd
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 135, 150, 170],
"costs": [80, 90, 95, 110],
})
fig = df.plot(x="month", y=["sales", "costs"], kind="line", backend="plotly")
fig.update_layout(title="Sales and costs", yaxis_title="Units")
fig.write_html("sales.html")The call returns a plotly.graph_objects.Figure, not a matplotlib Axes. Everything you learned about ax.set_xlabel or ax.figure.savefig no longer applies. You customize and save the figure through Plotly's own API, here update_layout and write_html.
Other libraries ship pandas backends too. hvplot (hvplot.pandas) and pandas-bokeh are two well-known ones. Each one registers itself, so installing the package is usually enough for the backend name to resolve.
What a backend changes and what it does not
A backend gets the data, the kind, and the keyword arguments. It decides what to do with them. Two consequences follow.
First, the common arguments are not guaranteed to work everywhere. The matplotlib-specific arguments in this tutorial, such as rot, figsize, marker, alpha, colormap and ax, belong to the matplotlib backend. Another backend may ignore them, raise an error, or give them a different meaning. Plotly, for example, takes layout settings through update_layout rather than figsize.
Second, the chart kinds can differ. The matplotlib backend supports line, bar, barh, hist, box, kde, density, area, pie, scatter and hexbin. A third-party backend usually supports a subset, and some add kinds of their own. Check the backend's documentation before you rely on a kind.
What stays the same is the front end. The x and y arguments, the kind argument and the df.plot.<kind> accessors work on any backend that supports the kind. Your data preparation also carries over unchanged: set_index, groupby, pivot_table and value_counts produce the same tables whatever draws them.
How pandas finds a backend
When you set the option, pandas resolves the name in this order:
- If the name is
matplotlib, it loads its built-in module. - It looks for an installed package that declares the
pandas_plot_backendsentry point with that name. This is how Plotly and hvplot register themselves. - It tries to import a module with that exact name.
The module is accepted only if it has a plot attribute. Otherwise pandas raises a ValueError that says the backend could not be found. The usual cause is a package that is not installed in the environment running your code. Check that first, especially in notebooks that use a different kernel from your terminal.
Step 3 means you can write a backend yourself. The next example builds a tiny one that prints text bars, to show the contract. It registers an in-memory module, so it runs as one script:
import sys
import types
import pandas as pd
def plot(data, kind, **kwargs):
"""Print a text bar for every value in every column."""
if isinstance(data, pd.Series):
data = data.to_frame()
x = kwargs.get("x")
if x is not None:
data = data.set_index(x)
y = kwargs.get("y")
if y is not None:
data = data[[y] if isinstance(y, str) else list(y)]
for column in data.columns:
print(f"{column} ({kind})")
for label, value in data[column].items():
print(f" {label:>4} {'#' * int(value // 10)} {value}")
backend = types.ModuleType("textbackend")
backend.plot = plot
sys.modules["textbackend"] = backend
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 135, 150, 170],
})
df.plot(x="month", y="sales", kind="bar", backend="textbackend")pandas passes x, y and kind to your function for DataFrames, along with any other keyword arguments you gave. A real backend would build a figure and return it. Real backends are usually separate packages, which declare the entry point in their packaging metadata.
Where df.plot runs out
df.plot is built for quick, single-chart exploration. You will hit its limits in predictable places.
- Annotations. Labeling one point, drawing a threshold line, or shading a date range needs Axes methods such as
annotate,axhlineandaxvspan. - Mixed chart types on one panel. A bar series with a line on a second y axis is awkward.
secondary_yhelps for lines, but it does not cover bars plus lines cleanly. - Irregular layouts.
subplots=Trueandlayoutgive an even grid. Panels of different sizes, shared legends, or an inset needplt.subplotswithgridspec_kworsubplot_mosaic. - Statistical charts. Grouped box plots with hue, regression fits, and faceting by a column are one-liners in seaborn and long-winded in
df.plot. - Interactivity. Hover tooltips, zoom and linked brushing require an interactive backend such as Plotly or hvplot, or a dashboard tool.
- Publication polish. Fine control of ticks, fonts, spacing and export formats is easier through matplotlib objects than through plot arguments.
You do not have to abandon df.plot the moment you need one of these. The ax argument lets you start with pandas and finish with matplotlib. Here a bar chart gets a second axis with a line, plus an annotation:
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")
margin = (data["sales"] - data["costs"]) / data["sales"] * 100
fig, ax = plt.subplots(figsize=(6, 4))
data["sales"].plot.bar(ax=ax, color="steelblue", rot=0)
ax.set_ylabel("Units sold")
ax2 = ax.twinx()
ax2.plot(range(len(data)), margin.to_numpy(), color="darkred", marker="o")
ax2.set_ylabel("Margin (%)")
best = int(margin.to_numpy().argmax())
ax2.annotate(
"Best margin",
xy=(best, margin.iloc[best]),
xytext=(best - 1, margin.iloc[best] + 3),
arrowprops={"arrowstyle": "->"},
)
fig.savefig("sales_margin.png", dpi=150, bbox_inches="tight")Bar charts from pandas place categories at positions 0, 1, 2 and so on. That is why the line on the second axis uses range(len(data)) for x. Using the month names there would create a new categorical axis that does not line up.
Choosing a tool
A few criteria apply to the choice.
- Audience. Charts only you will see favor
df.plot. Charts others will read, or interact with, justify the extra setup. - Portability. A global backend change affects every
df.plotcall in the session, including calls inside libraries you import. Prefer the per-callbackend=argument orpd.option_contextin shared code. - Dependencies. The matplotlib backend needs only matplotlib. Interactive backends add a package and, for notebooks, sometimes a front-end extension.
- Reproducibility. A script that sets
pd.options.plotting.backendshould do so near the top and say so in a comment. Otherwise a reader who calls.set_titleon the result will be confused by a Plotly figure.
Common mistakes
- Setting a backend that is not installed. The error appears when you set the option, not when you plot.
- Passing matplotlib-only arguments such as
figsizeorrotto another backend and expecting them to work. - Calling
plt.show()after a Plotly figure. Usefig.show()or write the figure to HTML. - Leaving a global backend set and then running older code that expects an Axes.
Exercise
A teammate sets pd.options.plotting.backend = "plotly" at the top of a shared notebook. Later, a cell runs ax = df.plot(kind="bar"); ax.set_title("Sales"), and it fails. Explain why, and give two ways to restore the old behavior for that cell without editing the first cell.
Show answer
With the Plotly backend, df.plot returns a Plotly Figure, which has no set_title method, so the call raises an AttributeError. Two fixes are to pass the backend for that call, df.plot(kind="bar", backend="matplotlib"), or to wrap the call in with pd.option_context("plotting.backend", "matplotlib"):. Resetting pd.options.plotting.backend = "matplotlib" in that cell also works, but it changes the setting for every later cell.
Exercise
You have a monthly bar chart of sales made with data["sales"].plot.bar(ax=ax). You add a line for margin on ax.twinx() and pass the month names as x values to ax2.plot. The line does not line up with the bars. What should you pass as x instead, and why?
Show answer
Pass integer positions such as range(len(data)). The pandas bar chart places its categories at positions 0, 1, 2 and so on, and labels them with the index values. Plotting with the month names creates a separate categorical axis, so the points do not match the bar positions.