svgbrushablecleveland-dot
Cleveland dot plot
How do categories compare on one value — and across up to three groups?
How to read it
- Compare the dots in a row to see how the groups differ inside one category.
- Read the line joining them as the size of that gap.
- Read the column of dots down the rows for how one group changes across categories.
- Callout 1: One dot per group in this row.
- Callout 2: The line joining dots: the gap between groups.
- Callout 3: No zero baseline: the axis zooms to the data's range.
Watch out
- The axis doesn't start at zero, so gaps look large. Check the scale before calling one big.
Defaults
- Aggregate
- Mean
- How rows combine into one number per group or period, such as a sum or a mean.
- Also: Sum · Median · Count
- Top N
- 12
- How many categories to show.
- Range 3 to 30, step 1
- Sort
- By value
- How rows are sorted.
- Also: Alphabetical
Pinned in the code
- Position on a common scale is the most accurately judged encoding (Cleveland & McGill 1984); the axis need not include zero because dots are read by position, not length.
- Rows are sorted by the aggregate over all rows (sum, mean, type-7 median or count); the first three group levels by frequency get a dot each.
- A thin segment spans the group values on a row so gaps are easy to read.
# Cleveland dot plot — Codesplash Chart Lab (recipe "cleveland-dot")
# controls: stat=mean, top=12, sort=value
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"]
df = pd.read_csv("cleveland-dot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["sex"] = pd.Categorical(df["sex"].astype("string"), categories=["Female", "Male"])
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
d = df.dropna(subset=["country", "life_expectancy"]).copy()
d["_cat"] = d["country"].astype(str)
overall = d.groupby("_cat")["life_expectancy"].agg("mean").rename("overall").reset_index() # orders the rows
overall = overall[np.isfinite(overall["overall"].astype(float))]
overall = overall.sort_values(["overall", "_cat"], ascending=[False, True]).head(12) # ties alphabetical
groups = levels(df["sex"])[:3] # first three group levels (dictionary order, else frequency)
d = d[d["sex"].notna()]
d["_g"] = d["sex"].astype(str)
cells = d[d["_g"].isin(groups)].groupby(["_cat", "_g"])["life_expectancy"].agg("mean").unstack()
cells = cells.reindex(index=overall["_cat"], columns=groups)
fig, ax = plt.subplots(figsize=(7, 5))
y = np.arange(len(cells))[::-1] # first row on top
ax.hlines(y, cells.min(axis=1), cells.max(axis=1), color="#9aa0a6", linewidth=2, zorder=1) # span of the group values
for j, grp in enumerate(groups):
ax.scatter(cells[grp], y, s=48, color=PALETTE[j], label=grp, zorder=2)
ax.set_yticks(y, cells.index)
ax.set_xlabel("Mean life_expectancy") # no zero baseline: dots are read by position
ax.set_ylabel("country")
ax.legend(title="sex")
plt.show()Needs pandas, numpy, matplotlib · reads cleveland-dot-demo.csv · app theme from the optional codesplash helper
# Cleveland dot plot — Codesplash Chart Lab (recipe "cleveland-dot")
# controls: stat=mean, top=12, sort=value
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("cleveland-dot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["sex"] = pd.Categorical(df["sex"].astype("string"), categories=["Female", "Male"])
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
d = df.dropna(subset=["country", "life_expectancy"]).copy()
d["_cat"] = d["country"].astype(str)
overall = d.groupby("_cat")["life_expectancy"].agg("mean").rename("overall").reset_index() # orders the rows
overall = overall[np.isfinite(overall["overall"].astype(float))]
overall = overall.sort_values(["overall", "_cat"], ascending=[False, True]).head(12) # ties alphabetical
groups = levels(df["sex"])[:3] # first three group levels (dictionary order, else frequency)
d = d[d["sex"].notna()]
d["_g"] = d["sex"].astype(str)
cells = d[d["_g"].isin(groups)].groupby(["_cat", "_g"])["life_expectancy"].agg("mean").unstack()
cells = cells.reindex(index=overall["_cat"], columns=groups)
fig = go.Figure()
for level, row in cells.iterrows(): # thin segment spanning the group values
fig.add_shape(type="line", x0=row.min(), x1=row.max(), y0=level, y1=level, line=dict(color="#9aa0a6", width=3), layer="below")
for j, grp in enumerate(groups):
fig.add_scatter(x=cells[grp], y=cells.index, mode="markers", name=grp, marker=dict(color=PALETTE[j], size=11))
fig.update_layout(xaxis_title="Mean life_expectancy", yaxis_title="country", yaxis_autorange="reversed", legend_title_text="sex")
fig.show()Needs pandas, numpy, plotly · reads cleveland-dot-demo.csv · app theme from the optional codesplash helper
# Cleveland dot plot — Codesplash Chart Lab (recipe "cleveland-dot")
# controls: stat=mean, top=12, sort=value
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("cleveland-dot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["country"]] <- factor(df[["country"]])
df[["sex"]] <- factor(df[["sex"]], levels = c("Female", "Male"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
cat <- as.character(df[["country"]])
val <- df[["life_expectancy"]]
ok <- !is.na(cat) & !is.na(val)
overall <- tapply(val[ok], cat[ok], mean) # the aggregate over all rows orders the rows
r <- data.frame(level = names(overall), overall = as.numeric(overall))
r <- r[is.finite(r$overall), ]
r <- head(r[order(-r$overall, r$level), ], 12) # ties alphabetical
groups <- head(levels(df[["sex"]]), 3) # first three group levels (dictionary order, else frequency)
grp <- as.character(df[["sex"]])
ok <- ok & !is.na(grp) & grp %in% groups
cells <- aggregate(list(value = val[ok]), list(level = cat[ok], group = grp[ok]), mean)
cells <- cells[cells$level %in% r$level, ]
cells$level <- factor(cells$level, levels = rev(r$level)) # first row on top
cells$group <- factor(cells$group, levels = groups)
span <- aggregate(value ~ level, cells, function(v) c(lo = min(v), hi = max(v)))
span <- data.frame(level = span$level, lo = span$value[, "lo"], hi = span$value[, "hi"])
p <- ggplot(cells, aes(value, level)) +
geom_segment(data = span, aes(x = lo, xend = hi, y = level, yend = level), colour = "#9aa0a6", linewidth = 1) +
geom_point(aes(colour = group), size = 3) +
scale_colour_manual(values = cs_cat, name = "sex") +
labs(x = "Mean life_expectancy", y = "country") + # no zero baseline: dots are read by position
theme_cs
print(p)Needs ggplot2 · reads cleveland-dot-demo.csv · app theme from the optional codesplashr helper
-- Cleveland dot plot — Codesplash Chart Lab (recipe "cleveland-dot")
-- controls: stat=mean, top=12, sort=value
-- Mean life_expectancy per category (overall and per group); rows sorted by the overall aggregate
SELECT "country"::VARCHAR AS level,
"sex"::VARCHAR AS grp,
avg("life_expectancy") AS value, count(*) AS n
FROM read_csv('cleveland-dot-demo.csv')
WHERE "country" IS NOT NULL AND "life_expectancy" IS NOT NULL
GROUP BY GROUPING SETS ((level), (level, grp))
ORDER BY grp NULLS FIRST, value DESC, level;Needs duckdb · reads cleveland-dot-demo.csv