Skip to content
svgbrushablebeeswarm

Beeswarm

Where exactly does every observation sit, without overlap, for small to medium groups?

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

How to read it

  1. Read each dot's vertical position: it sits at its exact value.
  2. The sideways spread only avoids overlap, so a wide swarm means many rows near that value.
  3. Compare the median lines across groups, then the swarm shapes.
  1. Callout 1: The line: this group's median.
  2. Callout 2: A wide swarm: many values close together.
  3. 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

  • 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.