How to Make a Beeswarm Plot in Python with Seaborn

Plot every data point without overlap using sns.swarmplot, fix the "points cannot be placed" warning, and combine beeswarms with groups, color and summaries.

A beeswarm plot shows every observation in each group, nudging points sideways so they don't overlap. In Python, use sns.swarmplot(data=df, x="group", y="value"). The width of the swarm shows where values are common. This post uses Seaborn 0.13.2 and Matplotlib 3.11.

Quick Example

Delivery times for three couriers:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng(199)
couriers = ["Bike", "Van", "Scooter"]
times = {
    "Bike": rng.normal(28, 4, 90),
    "Van": np.r_[rng.normal(24, 3, 60), rng.normal(41, 4, 30)],
    "Scooter": rng.gamma(9, 2.6, 90),
}
df = pd.DataFrame({
    "courier": np.repeat(couriers, 90),
    "minutes": np.concatenate([times[c] for c in couriers]).round(1),
    "rush_hour": rng.choice(["Rush hour", "Off-peak"], 270, p=[0.4, 0.6]),
    "distance_km": rng.uniform(1, 9, 270).round(1),
})

fig, ax = plt.subplots(figsize=(8, 4.8))
sns.swarmplot(data=df, x="courier", y="minutes", hue="courier",
              palette="Dark2", size=4.5, legend=False, ax=ax)
ax.set_xlabel("")
ax.set_ylabel("Delivery time (minutes)")
ax.set_title("Vans have two kinds of deliveries")
plt.show()

Beeswarm plot of delivery times by courier; bikes cluster around 28 minutes, vans split into two clusters and scooters have a long upper tail

A box plot would hide the two van clusters inside one wide box.

Fix "points cannot be placed" warnings

When there isn't room for every point, Seaborn drops the extra ones along the edges and warns, for example UserWarning: 25.7% of the points cannot be placed; you may want to decrease the size of the markers or use stripplot.

big = pd.DataFrame({"minutes": rng.normal(30, 5, 700)})

fig, axes = plt.subplots(1, 3, figsize=(10, 3.8), sharey=True)
sns.swarmplot(data=big, y="minutes", size=5, ax=axes[0])
axes[0].set_title("size=5: points dropped")
sns.swarmplot(data=big, y="minutes", size=2, ax=axes[1])
axes[1].set_title("size=2: all placed")
np.random.seed(0)                   # stripplot jitter is random
sns.stripplot(data=big, y="minutes", size=3, alpha=0.5, jitter=0.3,
              ax=axes[2])
axes[2].set_title("stripplot: random jitter")
plt.show()

Three panels of 700 points: large markers form flat-edged columns with points missing, small markers fit them all, and a strip plot scatters them randomly

Your options, in order:

  1. Make markers smaller with size.
  2. Make the figure wider (or taller for a horizontal swarm).
  3. Switch to stripplot(), violinplot() or a histogram once you have many hundreds of points per group.

The layout depends on the figure size at the moment it is drawn, so resize the figure before judging whether points fit.

Split by a second variable with hue

dodge=True puts each hue level in its own swarm.

fig, ax = plt.subplots(figsize=(9, 4.8))
sns.swarmplot(data=df, x="courier", y="minutes", hue="rush_hour", dodge=True,
              palette={"Rush hour": "#d1495b", "Off-peak": "#8d99ae"},
              size=3.5, ax=ax)
ax.set_xlabel("")
ax.set_ylabel("Delivery time (minutes)")
sns.move_legend(ax, "upper center", ncols=2, title=None)
ax.set_ylim(top=df.minutes.max() + 8)
plt.show()

Beeswarm plot with separate rush hour and off-peak swarms side by side for each courier

Without dodge=True, the two colors share one swarm.

Horizontal beeswarm colored by a number

Swap x and y to make it horizontal. A numeric hue with a continuous palette shows a third variable, here distance.

fig, ax = plt.subplots(figsize=(9, 4.5))
sns.swarmplot(data=df, x="minutes", y="courier", hue="distance_km",
              palette="viridis", size=4, ax=ax)
ax.set_xlabel("Delivery time (minutes)")
ax.set_ylabel("")
sns.move_legend(ax, "upper left", bbox_to_anchor=(1.01, 1), title="km")
plt.show()

Horizontal beeswarm plot with points colored by delivery distance

In this made-up data, distance was generated independently of time, so the colors are mixed throughout.

Add medians to a beeswarm

medians = df.groupby("courier").minutes.median().reindex(couriers)

fig, ax = plt.subplots(figsize=(8, 4.8))
sns.swarmplot(data=df, x="courier", y="minutes", order=couriers,
              color="#9aa5b1", size=4, ax=ax)
ax.hlines(medians, np.arange(3) - 0.35, np.arange(3) + 0.35,
          color="#111111", lw=3, zorder=3, label="Median")
for i, value in enumerate(medians):
    ax.text(i + 0.37, value, f"{value:.1f}", va="center", fontweight="bold")
ax.set_xlim(-0.5, 2.65)                   # room for the last label
ax.set_xlabel("")
ax.set_ylabel("Delivery time (minutes)")
ax.legend()
plt.show()

print(medians)
courier
Bike       28.9
Van        26.2
Scooter    21.4
Name: minutes, dtype: float64

Gray beeswarm plot with a black median line and value for each courier

For vans, the median falls in the larger, faster cluster and says nothing about the slow one. That's the case for showing the points.

Beeswarm, strip, violin or box plot?

Points per group Good choice
Under about 30 Beeswarm or strip plot
About 30 to 300 Beeswarm
More Violin plot, raincloud plot or box plot

SHAP "beeswarm" charts use the same idea for model explanations; see SHAP plots in Python.

Similar Topics