Sub topic 8
Titles, labels, colors, size and legend
This chapter covers the arguments of DataFrame.plot that change how a chart looks without changing what it shows. It assumes you can build a DataFrame, you know how set_index and kind choose the axes and chart type (earlier chapters), and matplotlib is installed.
Where styling arguments go
df.plot accepts most formatting options as keyword arguments. pandas passes them to matplotlib, either when it creates the figure or when it draws the lines, bars or markers. Two groups matter in practice:
- Figure-level options, such as
figsize, which are applied when pandas creates the figure. - Artist-level options, such as
color,linewidth,markerandalpha, which are applied to every drawn line, bar or marker.
Anything pandas does not expose as an argument can be changed afterwards through the returned Axes (covered in the next chapter).
Titles and axis labels
Three arguments set the text around the chart:
titlesets the chart title. Withsubplots=True, you can pass a list with one title per panel.xlabelandylabelset the axis labels. They exist in pandas 1.1 and later.fontsizesets the tick label size.
By default, the x label is the name of the index (df.index.name), and the y label is empty. If your index has a name you don't want shown, pass xlabel="" to hide it.
A fully styled line 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],
}).set_index("month")
ax = df.plot(
title="Sales and costs, January to April",
xlabel="Month",
ylabel="Units",
color={"sales": "#1f77b4", "costs": "tab:orange"},
figsize=(7, 4),
marker="o",
linewidth=2,
grid=True,
ylim=(0, 200),
legend=True,
)
ax.legend(loc="upper left", title="Series")
plt.show()The call combines every group from the diagram. marker and linewidth are matplotlib line properties that pandas forwards. The last line replaces the default legend with one placed in the upper left corner and given a title.
Colors
The color argument accepts several forms:
| Form | Example | Effect |
|---|---|---|
| One color | `color="steelblue"` | Every series or bar uses it |
| List | `color=["red", "green"]` | Colors are assigned in column order |
| Dict | `color={"sales": "navy"}` | Colors are assigned by column name |
| Hex string | `color="#2a9d8f"` | Any matplotlib color string works |
Dict form is the safest when you filter or reorder columns, because the color follows the column name and not its position. Columns missing from the dict get the default color.
For a smooth range of colors, use colormap, which takes a matplotlib colormap name such as "viridis" or "Set2". pandas samples the colormap evenly across the columns:
import numpy as np
rng = np.random.default_rng(1)
wide = pd.DataFrame(rng.normal(size=(30, 5)).cumsum(axis=0), columns=list("ABCDE"))
wide.plot(colormap="viridis", figsize=(7, 4), title="Five random walks")
plt.show()For a single bar series, a list of colors is applied per bar:
sales = df["sales"]
sales.plot.bar(color=["#264653", "#2a9d8f", "#e9c46a", "#e76f51"], rot=0)
plt.show()Figure size
figsize=(width, height) is measured in inches. The default is usually (6.4, 4.8), taken from matplotlib's rcParams["figure.figsize"]. The pixel size depends on the figure's dpi (dots per inch). A figsize=(6, 4) figure saved at dpi=150 is 900 by 600 pixels.
To change the size for all charts in a session, set it once:
plt.rcParams["figure.figsize"] = (8, 4)The legend
By default, a DataFrame plot shows a legend with one entry per column. A Series plot shows none. The legend argument controls this:
legend=Trueorlegend=Falseturns it on or off.legend="reverse"lists entries in reverse order. This is useful for stacked charts, where the visual stack order is the reverse of the column order.
Legend text comes from column names. The simplest way to change it is to rename the columns before plotting:
pretty = df.rename(columns={"sales": "Sales (units)", "costs": "Costs (units)"})
pretty.plot(legend="reverse", title="Renamed legend entries")
plt.show()For a Series, pass label and legend=True:
df["sales"].plot(label="Sales 2026", legend=True)
plt.show()To place the legend outside the plot area, call ax.legend on the returned Axes with an anchor. Use bbox_inches="tight" when saving, or the legend may be cut off:
ax = df.plot(title="Legend outside the axes")
ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1.0))
ax.figure.savefig("outside_legend.png", dpi=150, bbox_inches="tight")Other useful arguments
| Argument | What it does |
|---|---|
| `grid=True` | Draws grid lines |
| `alpha=0.5` | Sets transparency, from 0 to 1 |
| `rot=0` | Rotates x tick labels, in degrees |
| `xlim`, `ylim` | Set axis ranges as `(low, high)` tuples |
| `logy=True` | Uses a log scale on the y axis |
| `style="o--"` | Sets marker and line style with a matplotlib format string |
| `xticks`, `yticks` | Set tick positions |
style can also be a list or a dict with one format string per column, such as style={"sales": "o-", "costs": "s--"}.
Scatter plots use different color arguments
For kind="scatter", color sets one color for all points. To color points by a column, use c with a column name, and s for marker size. The legend is replaced by a colorbar, and colormap controls its palette:
people = pd.DataFrame({
"height": [150, 160, 170, 180, 190],
"weight": [50, 58, 68, 80, 92],
"age": [20, 35, 28, 50, 44],
})
people.plot.scatter(
x="height", y="weight", c="age", s=80, colormap="plasma",
title="Weight by height, colored by age",
)
plt.show()Common mistakes
colortogether withstyle. If thestylestring contains a color letter, such as"r--", and you also passcolor, pandas raises aValueError. Put the color in only one of them.- A color list that is too short. matplotlib repeats colors when there are more series than colors. Two series with a three-color list work. Five series with a two-color list produce repeated colors that look like errors.
figsizewithax. When you pass an existingax, pandas draws into that figure and ignoresfigsize. Set the size when you create the figure.- Legend overlapping data. The default
loc="best"is a guess. Pick a corner or move the legend outside. - Labels lost when saving. Without
bbox_inches="tight", long labels or an outside legend can be cropped in the saved file.
Practice
Exercise
You have df = pd.DataFrame({"month": ["Jan", "Feb", "Mar"], "a": [1, 2, 3], "b": [3, 2, 1]}). Write one call that draws a bar chart of columns a and b by month, with the title "A vs B", the y label "Count", no x label, a figure of 6 by 3 inches, the color of a set to "tab:green" and b set to "gray", and horizontal tick labels.
Show answer
df.setindex("month").plot.bar(title="A vs B", ylabel="Count", xlabel="", figsize=(6, 3), color={"a": "tab:green", "b": "gray"}, rot=0). The setindex call moves month to the x axis, the dict assigns colors by column name, xlabel="" hides the default label "month", and rot=0 keeps the tick labels horizontal.
Exercise
A line chart of three columns has its legend covering part of the data. How do you move the legend outside the plot on the right, and what must you do when saving the figure?
Show answer
Keep the Axes returned by plot, then call ax.legend(loc="upper left", bboxtoanchor=(1.02, 1.0)). When saving, call ax.figure.savefig("chart.png", bbox_inches="tight") so the legend outside the axes is included in the file.