Sub topic 7
Scatter Plots with Size and Color
This chapter assumes you can build a DataFrame, select columns, and call df.plot with x, y and kind. It also assumes matplotlib is installed. Here you will draw scatter plots with kind="scatter" and encode a third and fourth variable with marker size and color.
When to use a scatter plot
A scatter plot draws one marker per row. The horizontal position comes from one column and the vertical position from another. Use it to look for a relationship between two numeric variables, such as height and weight, or advertising spend and sales.
A scatter plot differs from the line chart in one way that matters. The line chart uses the index as the x axis by default. A scatter plot has no such default, so you must always name both x and y.
import pandas as pd
import matplotlib.pyplot as plt
cars = pd.DataFrame({
"weight": [1.2, 1.5, 1.8, 2.1, 2.4, 2.8, 3.1],
"mpg": [42, 38, 33, 29, 26, 22, 19],
"power": [70, 85, 100, 120, 140, 170, 200],
"origin": ["eu", "asia", "asia", "eu", "us", "us", "us"],
})
cars.plot.scatter(x="weight", y="mpg")
plt.show()The accessor cars.plot.scatter(...) is equivalent to cars.plot(kind="scatter", ...).
Why x and y are required
Other chart types can fall back on the index and on every numeric column. A scatter plot cannot, because it needs exactly one column for each axis. If you omit either one, pandas raises an error. The error message differs between versions, but it points at the missing argument.
# Raises an error because x and y are missing:
# cars.plot(kind="scatter")You can pass column names or integer positions. Names are easier to read and survive column reordering, so prefer them.
Encoding a third variable with size
The s argument sets the marker area, in points squared. You can pass a single number for uniform markers, or a column (or array) to vary the size by row.
cars.plot.scatter(
x="weight",
y="mpg",
s=cars["power"],
alpha=0.6,
title="Fuel economy by weight (size = power)",
)
plt.show()Here s is a Series, one value per row. Because s is an area, the raw values may produce markers that are too small or too large. Rescale them when needed:
sizes = cars["power"] * 2 # larger markers
sizes = cars["power"] ** 1.5 / 10 # emphasize big valuesBe careful when the values are very different. Size is judged by eye as area, so a value that is ten times larger looks about ten times larger in area, which is what you want. If you scaled a radius instead, the area would grow with the square and exaggerate the difference.
The alpha argument sets transparency from 0 (invisible) to 1 (opaque). Lower values help when markers overlap.
Encoding a variable with color
The c argument sets marker color. It accepts three kinds of input, and the difference is a common source of bugs.
| Input to `c` | Result |
|---|---|
| A color name or hex string, such as `"steelblue"` | All markers share one color |
| A column of numbers | Colors come from a colormap, and a colorbar is added |
| A list of color names, one per row | Each marker gets the color you specify |
For a numeric column, choose the colormap with colormap (or cmap):
cars.plot.scatter(
x="weight",
y="mpg",
c="power",
colormap="viridis",
s=80,
)
plt.show()Passing a column name as c is a pandas convenience. pandas looks the name up in the DataFrame and builds the colorbar for you. The colorbar is labeled with the column name.
If you pass colorbar=False, the colors are still mapped but the legend for them disappears. Keep the colorbar in most cases, because without it the reader cannot decode the colors.
Coloring by category
A categorical column such as origin holds strings. If you pass it as c, matplotlib cannot treat the strings as numbers, so the call fails or gives colors you did not expect. Map each category to a color yourself:
palette = {"eu": "tab:blue", "asia": "tab:orange", "us": "tab:green"}
colors = cars["origin"].map(palette)
cars.plot.scatter(x="weight", y="mpg", c=colors, s=80)
plt.show()This works, but it gives no legend, because only one scatter call is made. To get a legend, draw one scatter per category on a shared Axes. The ax argument tells pandas where to draw:
fig, ax = plt.subplots(figsize=(6, 4))
for name, group in cars.groupby("origin"):
group.plot.scatter(
x="weight",
y="mpg",
ax=ax,
label=name,
color=palette[name],
s=80,
)
ax.legend(title="Origin")
plt.show()Each call adds markers to the same Axes, and label feeds the legend. Note the argument is color here, because each group has a single color. This loop is the standard way to build a categorical legend with df.plot.
Combining size and color
You can use both at once to show four variables in one chart: two positions, one size and one color.
cars.plot.scatter(
x="weight",
y="mpg",
s=cars["power"] * 1.5,
c="power",
colormap="plasma",
alpha=0.7,
figsize=(6, 4),
title="Weight vs. mpg",
)
plt.show()Here size and color both encode power, which is redundant. That is useful for readability, because the two cues reinforce each other. To encode a different variable, use another column for s. More than four encodings quickly makes the chart hard to read, so stop there.
How the arguments reach matplotlib
Internally, pandas builds the arguments and calls matplotlib's Axes.scatter. Any extra keyword that Axes.scatter understands, such as marker, edgecolors or linewidths, is passed through:
cars.plot.scatter(
x="weight",
y="mpg",
s=100,
marker="D",
edgecolors="black",
linewidths=1,
color="gold",
)
plt.show()Common errors and edge cases
- Missing x or y. A scatter plot always needs both. Pass them by name.
- Non-numeric x or y. Strings on an axis do not give a useful scatter. Convert the column with
pd.to_numericor use another chart type. - Missing values. Rows with
NaNinxoryare dropped from the plot without a warning. If points seem to be missing, checkcars[["weight", "mpg"]].isna().sum(). - Size column with negative or zero values. A zero gives an invisible marker, and a negative value is invalid. Shift or rescale the values first.
- Categorical
c. Strings cannot go through a colormap. Map them to colors, or loop over groups as shown above. - Overplotting. With thousands of points, markers pile up. Use a small
s, a lowalpha, or switch tokind="hexbin"withgridsize, which counts points per cell.
import numpy as np
rng = np.random.default_rng(1)
big = pd.DataFrame({"x": rng.normal(size=5000)})
big["y"] = big["x"] * 0.5 + rng.normal(size=5000)
big.plot.hexbin(x="x", y="y", gridsize=25, cmap="Blues")
plt.show()Exercise
You have a DataFrame df with numeric columns price, rating and sales, and a string column brand with three values. Write the call that draws a scatter of price against rating with marker size from sales and a colorbar for sales. Then explain why passing c="brand" would not work, and what to do instead if you want brand colors with a legend.
Show answer
Use df.plot.scatter(x="price", y="rating", s=df["sales"], c="sales", colormap="viridis", alpha=0.7). You can rescale s if the markers are too small or large. Passing c="brand" fails or misbehaves because the values are strings, and a colormap needs numbers. Instead, create a Matplotlib Axes with fig, ax = plt.subplots(), loop over df.groupby("brand"), call group.plot.scatter(x="price", y="rating", ax=ax, label=name, color=palette[name]) for each group, and then call ax.legend().