svgbrushablebubble
Bubble chart
How do two variables relate when a third sets each point's weight?
How to read it
- Read position as for any scatter: the two main variables.
- Read bubble area as the third variable; use the size legend.
- Colour marks the group: look for groups that sit apart.
- Callout 1: Large bubbles: heavy rows, which can hide the small ones.
- Callout 2: Size legend: area shows the value.
- 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
# Bubble chart — Codesplash Chart Lab (recipe "bubble")
# controls: logX=true, scale=1, labels=5
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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"])
d = df.dropna(subset=["gdp_per_capita_k", "life_expectancy", "population_m"])
d = d[d["gdp_per_capita_k"] > 0]
d = d[d["population_m"] > 0].sort_values("population_m", ascending=False, kind="stable") # largest first
fig = px.scatter(d, x="gdp_per_capita_k", y="life_expectancy", size="population_m", size_max=44, color="region", color_discrete_sequence=PALETTE, symbol="region", symbol_sequence=SERIES_MARKERS, hover_name="country", log_x=True) # shape per colour group, as in the app
# plotly sizes markers by area (sizemode='area'), like the app
top = d.head(5)
fig.add_scatter(x=top["gdp_per_capita_k"], y=top["life_expectancy"], text=top["country"].astype(str), mode="text", textfont_size=10, showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads bubble-demo.csv · app theme from the optional codesplash helper
# Bubble chart — Codesplash Chart Lab (recipe "bubble")
# controls: logX=true, scale=1, labels=5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("bubble-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("Africa", "Americas", "Asia", "Europe", "Oceania"))
df[["country"]] <- factor(df[["country"]])
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
d <- df[stats::complete.cases(df[c("gdp_per_capita_k", "life_expectancy", "population_m")]), , drop = FALSE]
d <- d[d[["gdp_per_capita_k"]] > 0, , drop = FALSE] # log axis: x <= 0 cannot be drawn
d <- d[d[["population_m"]] > 0, , drop = FALSE] # zero/negative sizes draw no bubble
d <- d[order(-d[["population_m"]]), , drop = FALSE] # largest first so small bubbles stay visible
p <- ggplot(d, aes(x = .data[["gdp_per_capita_k"]], y = .data[["life_expectancy"]], size = .data[["population_m"]])) +
geom_point(aes(colour = .data[["region"]], shape = .data[["region"]]), alpha = 0.75) + # shape per colour group, as in the app
scale_colour_manual(values = cs_cat, name = "region") + scale_shape_manual(values = cs_shapes, name = "region") +
scale_size_area(max_size = 16, name = "population_m") + # area ∝ value
geom_text(data = utils::head(d, 5), aes(label = .data[["country"]]), size = 3, show.legend = FALSE) +
scale_x_log10() +
labs(x = "gdp_per_capita_k", y = "life_expectancy") +
theme_cs
print(p)Needs ggplot2 · reads bubble-demo.csv · app theme from the optional codesplashr helper
-- Bubble chart — Codesplash Chart Lab (recipe "bubble")
-- controls: logX=true, scale=1, labels=5
-- bubbles largest first; radius relative to the largest bubble = sqrt(v / v_max) (area ∝ value)
SELECT "region", "country", "gdp_per_capita_k", "life_expectancy", "population_m",
sqrt("population_m" / max("population_m") OVER ()) AS radius_rel
FROM read_csv('bubble-demo.csv')
WHERE "gdp_per_capita_k" IS NOT NULL AND "life_expectancy" IS NOT NULL AND "population_m" > 0 AND "gdp_per_capita_k" > 0
ORDER BY "population_m" DESC;Needs duckdb · reads bubble-demo.csv