svgbrushablebeeswarm
Beeswarm
Where exactly does every observation sit, without overlap, for small to medium groups?
How to read it
- Read each dot's vertical position: it sits at its exact value.
- The sideways spread only avoids overlap, so a wide swarm means many rows near that value.
- Compare the median lines across groups, then the swarm shapes.
- Callout 1: The line: this group's median.
- Callout 2: A wide swarm: many values close together.
- Callout 3: Compare swarm positions across groups.
Watch out
- Above about 1,000 points per group the swarm overflows. Use a violin or a box plot.
Defaults
- Point radius
- 3
- The size of each point.
- Range 1.5 to 6, step 0.5
- Median line
- On
- Mark each group's median.
Pinned in the code
- Greedy swarm in value order: each point takes the smallest sideways offset (alternating sides) that keeps circles of radius r apart; values are never shifted (`beeswarm` swarm method, seaborn `swarmplot`).
- If a swarm is wider than its band it is compressed horizontally (positions along the value axis are exact).
- Median: type 7.
# Beeswarm — Codesplash Chart Lab (recipe "beeswarm")
# controls: size=3, median=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
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"]
df = pd.read_csv("beeswarm-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["ward"] = pd.Categorical(df["ward"].astype("string"), categories=["Cardiology", "Maternity", "Pediatrics"])
def groups(frame, value, group=None, max_levels=12):
"""(label, values) per group in level order; rows missing the value or the group are dropped."""
if group is None:
return [(value, frame[value].dropna().to_numpy(dtype=float))]
d = frame[[value, group]].dropna()
out = []
for level in list(d[group].cat.categories)[:max_levels]:
v = d.loc[d[group] == level, value].to_numpy(dtype=float)
if v.size:
out.append((str(level), v))
return out
parts = groups(df, "age", "ward", max_levels=8)
long = pd.DataFrame({"group": np.repeat([label for label, _ in parts], [v.size for _, v in parts]), "value": np.concatenate([v for _, v in parts])})
fig, ax = plt.subplots(figsize=(7, 4))
# seaborn's swarm: greedy, values never shifted (the app's layout is the same idea, in its own pixel grid)
sns.swarmplot(data=long, x="group", y="value", hue="group", order=[label for label, _ in parts], palette=[PALETTE[i % len(PALETTE)] for i in range(len(parts))],
size=3, legend=False, warn_thresh=1, ax=ax)
for i, (_, v) in enumerate(parts):
ax.hlines(np.median(v), i - 0.4, i + 0.4, color=plt.rcParams["text.color"], linewidth=1.5) # type-7 median
ax.set_xlabel("ward")
ax.set_ylabel("age")
plt.show()Needs pandas, numpy, matplotlib, seaborn · reads beeswarm-demo.csv · app theme from the optional codesplash helper
# Beeswarm — Codesplash Chart Lab (recipe "beeswarm")
# controls: size=3, median=true
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
df = pd.read_csv("beeswarm-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["ward"] = pd.Categorical(df["ward"].astype("string"), categories=["Cardiology", "Maternity", "Pediatrics"])
def groups(frame, value, group=None, max_levels=12):
"""(label, values) per group in level order; rows missing the value or the group are dropped."""
if group is None:
return [(value, frame[value].dropna().to_numpy(dtype=float))]
d = frame[[value, group]].dropna()
out = []
for level in list(d[group].cat.categories)[:max_levels]:
v = d.loc[d[group] == level, value].to_numpy(dtype=float)
if v.size:
out.append((str(level), v))
return out
def swarm(pos, r):
"""The app's greedy swarm: in value order, each point takes the smallest sideways offset
(alternating sides) that keeps circles of radius r apart. pos and r are in pixels."""
order = np.argsort(pos, kind="stable")
placed, out, start = [], np.zeros(pos.size), 0
for i in order:
x = pos[i]
while start < len(placed) and placed[start][0] < x - 2 * r:
start += 1
best = 0.0
for step in range(400):
y = 0.0 if step == 0 else (1 if step % 2 else -1) * np.ceil(step / 2) * r * 0.9
if all((px_ - x) ** 2 + (py_ - y) ** 2 >= (2 * r) ** 2 for px_, py_ in placed[start:]):
best = y
break
placed.append((x, best))
out[i] = best
return out
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
parts = groups(df, "age", "ward", max_levels=8)
W, H = 640, 360 # the plot size (pixels) the layout is computed for
R = 3 # point radius in pixels
pooled = np.concatenate([v for _, v in parts])
lo, hi = pooled.min(), pooled.max()
band = W / len(parts)
fig = go.Figure()
for i, (label, v) in enumerate(parts):
off = swarm((v - lo) / ((hi - lo) or 1) * H, R)
widest = np.abs(off).max()
if widest > 0.45 * band: # a swarm wider than its band is compressed horizontally
off *= 0.45 * band / widest
fig.add_scatter(x=i + off / band, y=v, mode="markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=2 * R), name=label, showlegend=False)
fig.add_shape(type="line", x0=i - 0.4, x1=i + 0.4, y0=np.median(v), y1=np.median(v), line=dict(color=INK, width=2)) # type-7 median
fig.update_layout(width=W + 120, height=H + 110, xaxis=dict(tickvals=list(range(len(parts))), ticktext=[label for label, _ in parts], title="ward"), yaxis_title="age")
fig.show()Needs pandas, numpy, plotly · reads beeswarm-demo.csv · app theme from the optional codesplash helper
# Beeswarm — Codesplash Chart Lab (recipe "beeswarm")
# controls: size=3, median=true
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))
df <- read.csv("beeswarm-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["ward"]] <- factor(df[["ward"]], levels = c("Cardiology", "Maternity", "Pediatrics"))
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
swarm <- function(pos, r) {
# the app's greedy swarm: in value order, each point takes the smallest sideways offset
# (alternating sides) that keeps circles of radius r apart; pos and r are in pixels
out <- numeric(length(pos)); px <- numeric(0); py <- numeric(0); start <- 1
for (i in order(pos)) {
x <- pos[i]
while (start <= length(px) && px[start] < x - 2 * r) start <- start + 1
near <- if (start <= length(px)) start:length(px) else integer(0)
best <- 0
for (step in 0:399) {
y <- if (step == 0) 0 else (if (step %% 2 == 1) 1 else -1) * ceiling(step / 2) * r * 0.9
if (all((px[near] - x)^2 + (py[near] - y)^2 >= (2 * r)^2)) { best <- y; break }
}
px <- c(px, x); py <- c(py, best); out[i] <- best
}
out
}
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
parts <- groups_of(df, "age", "ward", max_levels = 8)
W <- 640; H <- 360 # the plot size (pixels) the layout is computed for
R <- 3 # point radius in pixels
pooled <- unlist(parts, use.names = FALSE)
rng <- range(pooled); band <- W / length(parts)
pts <- do.call(rbind, lapply(seq_along(parts), function(i) {
v <- parts[[i]]
off <- swarm((v - rng[1]) / max(diff(rng), 1e-12) * H, R)
if (max(abs(off)) > 0.45 * band) off <- off * 0.45 * band / max(abs(off)) # compress a swarm wider than its band
data.frame(group = names(parts)[i], pos = i - 1 + off / band, value = v)
}))
pts$group <- factor(pts$group, levels = names(parts))
p <- ggplot(pts, aes(pos, value, colour = group)) +
geom_point(size = 3 * 0.55, show.legend = FALSE) +
scale_colour_manual(values = rep(cs_cat, length.out = length(parts))) +
scale_x_continuous(breaks = seq_along(parts) - 1, labels = names(parts)) +
labs(x = "ward", y = "age") + theme_cs
med <- data.frame(i = seq_along(parts) - 1, m = vapply(parts, median, 0)) # type-7 median
p <- p + geom_segment(data = med, aes(x = i - 0.4, xend = i + 0.4, y = m, yend = m), inherit.aes = FALSE, colour = ink, linewidth = 0.8)
print(p)Needs ggplot2 · reads beeswarm-demo.csv · app theme from the optional codesplashr helper
- matplotlib uses seaborn's swarmplot; plotly and R port the app's greedy layout for a 640 × 360 px plot. Offsets are cosmetic — values are never shifted.
- A swarm is a point layout, not an aggregate, so there is no geometry SQL.