Sub topic 7
Scatter plots with size and color
A scatter plot shows each row of a DataFrame as one point. It suits two numeric columns that you want to compare. This chapter assumes you can build a DataFrame, select columns, and call df.plot with kind or the df.plot.<kind> accessors. Matplotlib must be installed.
Why scatter needs x and y
Line and bar charts can use the index for the x axis. A scatter plot cannot. It needs two columns, so you must pass both x and y. If you leave one out, pandas raises an error.
import pandas as pd
import matplotlib.pyplot as plt
cars = pd.DataFrame({
"weight": [1.2, 1.5, 1.8, 2.1, 2.4, 2.9, 3.2],
"mpg": [42, 38, 33, 30, 26, 22, 19],
"power": [70, 85, 100, 120, 140, 180, 210],
"origin": ["EU", "JP", "JP", "EU", "US", "US", "US"],
})
cars.plot.scatter(x="weight", y="mpg", title="Weight vs fuel economy")
plt.show()cars.plot(kind="scatter", x="weight", y="mpg") gives the same chart. Each point is one car. The downward trend shows that heavier cars get fewer miles per gallon.
Encoding a third value with size
The s argument sets the marker area. You can pass one number, or a column, so that each point gets its own size. This is a bubble chart.
cars.plot.scatter(
x="weight",
y="mpg",
s=cars["power"],
alpha=0.6,
)
plt.show()Marker area is measured in points squared. Raw values like 70 to 210 give small, similar-looking bubbles. Scale the column to make differences easier to see, for example s=cars["power"] * 2. The alpha argument makes markers partly transparent so overlapping points stay visible.
Encoding a value with color
The c argument colors points. Its meaning depends on what you pass.
- A single color name such as
"tomato"colors every point the same. - A numeric column maps values to a color scale. Use
colormapto choose the scale, and pandas adds a color bar. - A list of color names colors each point individually.
ax = cars.plot.scatter(
x="weight",
y="mpg",
c="power",
colormap="viridis",
s=80,
)
ax.set_xlabel("Weight (tonnes)")
ax.set_ylabel("Miles per gallon")
plt.show()You can also pass a column name as a string, as in c="power". For a numeric column, pandas looks it up in the DataFrame and draws a color bar. For a text column such as origin, there is no automatic scale. Map each category to a color first.
palette = {"EU": "tab:blue", "JP": "tab:red", "US": "tab:green"}
cars.plot.scatter(
x="weight",
y="mpg",
c=cars["origin"].map(palette),
s=cars["power"],
alpha=0.7,
)
plt.show()This version shows three variables beyond position: size for power, color for origin, and the two axes. pandas does not draw a legend for category colors here. If readers need one, plot each group separately on a shared Axes.
fig, ax = plt.subplots()
for name, group in cars.groupby("origin"):
group.plot.scatter(x="weight", y="mpg", ax=ax, label=name, color=palette[name])
plt.show()The ax argument tells each call to draw on the same Axes, and label feeds the legend.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError` about `x` and `y` | One of them is missing | Pass both column names |
| Error about no numeric data | A plotted column holds text | Convert with `pd.to_numeric` or pick another column |
| Tiny or identical bubbles | Raw values used as areas | Multiply or rescale the size column |
| Color bar missing | `c` is a single color or a text column | Pass a numeric column |
Exercise
You have a DataFrame with numeric columns "height", "weight" and "age". Write the call that plots height on x and weight on y, colors points by age with a color bar, and makes points semi-transparent.
Show answer
df.plot.scatter(x="height", y="weight", c="age", colormap="viridis", alpha=0.6). Passing the numeric column "age" to c maps its values to the color scale and adds a color bar, and alpha sets the transparency.