Sub topic 8
Titles, labels, colors, size and legend
This chapter assumes you can build a DataFrame, call df.plot(), and choose a chart type with kind. It covers the arguments that make a chart readable: title, axis labels, colors, figure size, and legend. Matplotlib must be installed.
Styling through plot arguments
DataFrame.plot accepts styling arguments directly, so you can often skip matplotlib calls. The most common ones are in the table.
| Argument | Effect | Example |
|---|---|---|
| `title` | Text above the chart | `title="Monthly sales"` |
| `xlabel`, `ylabel` | Axis labels | `ylabel="Units sold"` |
| `color` | One color, or a list or dict of colors | `color="steelblue"` |
| `figsize` | Width and height in inches | `figsize=(6, 4)` |
| `legend` | Show or hide the legend | `legend=False` |
| `grid` | Show grid lines | `grid=True` |
| `rot` | Rotate tick labels in degrees | `rot=0` |
| `fontsize` | Tick label size | `fontsize=10` |
The xlabel and ylabel arguments exist in current pandas versions. In older versions, set labels on the returned Axes instead, as shown later in this chapter.
A fully labeled chart
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],
})
df.set_index("month").plot(
title="Sales and costs, January to April",
xlabel="Month",
ylabel="Units",
figsize=(7, 4),
color=["steelblue", "darkorange"],
marker="o",
grid=True,
)
plt.show()The color list matches the columns in order: sales is blue and costs is orange. A dict also works and is safer when column order might change:
colors = {"sales": "seagreen", "costs": "firebrick"}
df.set_index("month").plot.bar(color=colors, rot=0)
plt.show()Colors can be names ("steelblue"), hex strings ("#4c72b0"), or matplotlib short codes ("r", "g").
Controlling the legend
With several columns, pandas draws a legend using the column names. With a single column it still shows one entry, which is often redundant because the title already says what the chart shows. Turn it off with legend=False.
df.set_index("month")["sales"].plot.bar(
title="Monthly sales",
legend=False,
rot=0,
)
plt.show()To move the legend, use the returned Axes:
ax = df.set_index("month").plot(marker="o")
ax.legend(loc="upper left", title="Measure")
plt.show()Legend entries come from the column names. To change them, rename the columns before plotting, for example df.rename(columns={"sales": "Units sold"}).
Common mistakes
- Wrong color count. Passing a list shorter than the number of columns makes pandas cycle the colors, so two lines can look identical.
- Setting
figsizeafter plotting. The size is fixed when the figure is created. Passfigsizein theplotcall. - Expecting
titleto be a list. Withsubplots=True, a list of titles gives one title per panel. Without subplots, a list raises an error.
Exercise
You plot a DataFrame with columns "north" and "south" using df.plot.bar(color=["red"]). What do you expect to see, and how would you fix it?
Show answer
Only one color is supplied for two columns, so pandas cycles it and both bars are red, which makes the legend useless. Fix it by passing two colors, for example color=["red", "blue"], or a dict such as color={"north": "red", "south": "blue"}.
Exercise
Write the plot call for a single-column Series s that shows a title "Daily visits", a y label "Visits", a figure 8 inches wide and 3 inches tall, and no legend.
Show answer
s.plot(title="Daily visits", ylabel="Visits", figsize=(8, 3), legend=False)