Skip to content
svgbrushablebubble

Bubble chart

How do two variables relate when a third sets each point's weight?

Demo data · seed 20261101 · 72 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read position as for any scatter: the two main variables.
  2. Read bubble area as the third variable; use the size legend.
  3. Colour marks the group: look for groups that sit apart.
  1. Callout 1: Large bubbles: heavy rows, which can hide the small ones.
  2. Callout 2: Size legend: area shows the value.
  3. Callout 3: Labels on the largest points.

Watch out

  • People judge area poorly, so don't read exact ratios from bubble sizes.

Defaults

Log X axis
On
Space the x axis by ratios, which suits values spanning orders of magnitude.
Bubble scale
1
Make all bubbles larger or smaller; their relative areas stay the same.
Range 0.5 to 2, step 0.25
Label largest
5
Name the largest bubbles.
Range 0 to 20, step 1

Pinned in the code

  • Area ∝ value: r = r_max·√(v / v_max) (ggplot2 `scale_size_area`), so twice the value has twice the ink; zero and negative sizes draw no bubble.
  • Bubbles are drawn largest first so smaller ones stay visible; rows missing x, y or size are dropped (and x ≤ 0 on a log axis).
  • Size legend values are round numbers ≤ the maximum at about 1, ¼ and 1⁄16 of it (radii ≈ 1, ½, ¼).

Use with care

People judge areas poorly; keep the size variable secondary and give exact values in tooltips or a table.

# Bubble chart — Codesplash Chart Lab (recipe "bubble")
# controls: logX=true, scale=1, labels=5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("bubble-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["Africa", "Americas", "Asia", "Europe", "Oceania"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

d = df.dropna(subset=["gdp_per_capita_k", "life_expectancy", "population_m"])
d = d[d["gdp_per_capita_k"] > 0]  # log axis: x ≤ 0 cannot be drawn
d = d.sort_values("population_m", ascending=False, kind="stable")  # largest first, small bubbles on top
v = d["population_m"].clip(lower=0).to_numpy(dtype=float)  # zero/negative sizes draw no bubble
area = (22 ** 2) * v / v.max()  # area ∝ value (ggplot2 scale_size_area)

fig, ax = plt.subplots(figsize=(7, 4.5))
levels = freq_levels(d["region"])
key = d["region"].astype(str).to_numpy()
# each colour group also gets its own marker shape (same area), as in the app; other levels use the 8th
groups = [(lv, key == lv, i) for i, lv in enumerate(levels)] + [(None, ~np.isin(key, levels), 7)]
for lv, m, i in groups:
    if m.any():
        ax.scatter(d["gdp_per_capita_k"][m], d["life_expectancy"][m], s=area[m], color=PALETTE[i % len(PALETTE)], marker=SERIES_MARKERS[i % 8], alpha=0.7, edgecolors="white", linewidths=0.6)
    if lv is not None:
        ax.scatter([], [], color=PALETTE[i % len(PALETTE)], marker=SERIES_MARKERS[i % 8], label=lv)
ax.legend(title="region", fontsize=8)
for _, row in d.head(5).iterrows():  # label the 5 largest
    ax.annotate(str(row["country"]), (row["gdp_per_capita_k"], row["life_expectancy"]), fontsize=8, ha="center", va="center")
ax.set_xscale("log")
ax.set_xlabel("gdp_per_capita_k (log scale)")
ax.set_ylabel("life_expectancy")
ax.set_title("Bubble area proportional to population_m", fontsize=10, loc="left")
plt.show()

Needs pandas, numpy, matplotlib · reads bubble-demo.csv · app theme from the optional codesplash helper