A scatter plot puts one dot per item, with one number on the x-axis and another on the y-axis. It answers the question: are these two things related? Do students who study longer score higher? Do bigger flats cost more? It also reveals clusters, gaps and outliers that summary numbers hide.
This lesson shows how to make scatter plots with ax.scatter, colour and size points to add more information, deal with thousands of overlapping points, and add a trend line. We'll use Seaborn's built-in penguins dataset, real measurements of 344 penguins, which downloads automatically the first time.
The data
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
penguins = sns.load_dataset("penguins").dropna()
print(penguins.shape)
print(penguins[["species", "flipper_length_mm", "body_mass_g"]].head(3))
(333, 7)
species flipper_length_mm body_mass_g
0 Adelie 181.0 3750.0
1 Adelie 186.0 3800.0
2 Adelie 195.0 3250.0
dropna() removes the rows with missing measurements; finding missing values is covered in filter rows in pandas. We only use Seaborn here to load the data; the charts are pure Matplotlib.
A basic scatter plot
fig, ax = plt.subplots()
ax.scatter(penguins["flipper_length_mm"], penguins["body_mass_g"])
ax.set_title("Penguins with longer flippers are heavier")
ax.set_xlabel("Flipper length (mm)")
ax.set_ylabel("Body mass (g)")
plt.show()
The cloud of points slopes upwards: a strong positive relationship. A downward slope would be a negative relationship, and a shapeless blob means no clear relationship. The statistics for machine learning lesson shows how to measure this as a correlation.
Colour points by group
The upward cloud seems to have two clumps. Colour by species to see why. Plot each group separately with its own label:
fig, ax = plt.subplots()
for species, group in penguins.groupby("species"):
ax.scatter(group["flipper_length_mm"], group["body_mass_g"],
label=species, alpha=0.7)
ax.set_xlabel("Flipper length (mm)")
ax.set_ylabel("Body mass (g)")
ax.legend(title="Species")
plt.show()
Now the story is richer: Gentoo penguins form their own cluster, bigger in both measures. Adding a third variable through colour often reveals what's really going on. Seaborn does this in one line with hue="species", as you'll see in the Seaborn module.
Colour points by a number
For a numeric third variable, pass it as c with a colormap, and add a colour bar as the key:
fig, ax = plt.subplots()
points = ax.scatter(penguins["flipper_length_mm"], penguins["body_mass_g"],
c=penguins["bill_length_mm"], cmap="viridis")
fig.colorbar(points, ax=ax, label="Bill length (mm)")
ax.set_xlabel("Flipper length (mm)")
ax.set_ylabel("Body mass (g)")
plt.show()
viridis runs from dark purple to yellow and is designed to be readable by people with colour vision deficiency and in greyscale. Avoid rainbow colormaps like jet, which create false boundaries.
Size points by a number
The s option sets marker size in points squared, and it can be a column too. This makes a bubble chart:
cities = ["Kanpur", "Lucknow", "Pune", "Jaipur", "Indore"]
literacy = [84, 82, 90, 84, 86]
income = [180, 210, 320, 230, 240] # ₹ thousand per year, illustrative
population = [3.2, 3.9, 7.4, 4.1, 3.3] # millions
fig, ax = plt.subplots()
ax.scatter(literacy, income, s=[p * 150 for p in population], alpha=0.5)
for name, x, y in zip(cities, literacy, income):
ax.annotate(name, (x, y), ha="center", va="center")
ax.set_xlabel("Literacy rate (%)")
ax.set_ylabel("Average income (₹ thousand)")
ax.set_title("Bubble size = population")
plt.show()
People judge circle sizes poorly, so use bubble sizes for rough impressions only, and label bubbles when there are few of them.
Too many points: overplotting
With thousands of points, they pile up into a solid blob and you can't see where most of them are. Three fixes:
rng = np.random.default_rng(0)
x = rng.normal(0, 1, 20_000)
y = x + rng.normal(0, 1, 20_000)
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].scatter(x, y)
axes[0].set_title("Overplotted")
axes[1].scatter(x, y, s=3, alpha=0.1)
axes[1].set_title("Small, transparent points")
axes[2].hexbin(x, y, gridsize=40, cmap="Blues")
axes[2].set_title("Hexbin: counts per hexagon")
fig.tight_layout()
plt.show()
- Smaller, transparent points (
s,alpha): dense areas become darker. hexbindivides the area into hexagons and colours each by how many points fall in it.- Or sample the data: plotting 2,000 random points often shows the same pattern.
Add a trend line
A straight trend line makes the relationship easier to see. np.polyfit finds the best-fit line, the same idea as linear regression:
x = penguins["flipper_length_mm"]
y = penguins["body_mass_g"]
slope, intercept = np.polyfit(x, y, 1)
print(f"Each extra mm of flipper adds about {slope:.0f} g")
fig, ax = plt.subplots()
ax.scatter(x, y, alpha=0.5)
line_x = np.array([x.min(), x.max()])
ax.plot(line_x, slope * line_x + intercept, color="crimson", lw=2)
ax.set_xlabel("Flipper length (mm)")
ax.set_ylabel("Body mass (g)")
plt.show()
Each extra mm of flipper adds about 50 g
Remember: a relationship isn't proof that one thing causes the other.
Practice
- Plot bill length against bill depth for the penguins, coloured by species. What do you notice?
Show the answer
fig, ax = plt.subplots()
for species, group in penguins.groupby("species"):
ax.scatter(group["bill_length_mm"], group["bill_depth_mm"], label=species)
ax.legend()
plt.show()
Overall the two seem slightly negatively related, but within each species the relationship is positive. Colouring by group reveals this; it's an example of Simpson's paradox.
- Use triangle markers of size 60 with black edges.
Show the answer
ax.scatter(x, y, marker="^", s=60, edgecolor="black")
- You have 500,000 points. Name two ways to make the scatter plot readable.
Show the answer
Use small markers with low alpha, use hexbin or a 2D histogram, or plot a random sample.
Interview questions
What does a scatter plot show?
The relationship between two numeric variables, one point per observation: the direction and strength of the relationship, its shape (linear or curved), clusters and outliers.
How do you show a third variable on a scatter plot?
Colour (c with a colormap and colour bar, or separate groups with a legend), marker size (s, making a bubble chart), or marker shape.
What is overplotting and how do you fix it?
When many points overlap so densities can't be seen. Fixes include transparency, smaller markers, sampling, hexbin or 2D histogram plots, and density contours.
What to learn next
- Show how one variable is spread with histograms in Matplotlib.
- Compare groups' spreads with box plots in Matplotlib.