svgbrushableraincloud
Raincloud
How do groups compare in shape, summary and individual observations at once?
How to read it
- Read the cloud for each group's shape.
- Read the box for its median and middle half.
- Read the rain to check the summaries against the real observations and spot gaps or clumps.
- Callout 1: Cloud: the shape of the distribution.
- Callout 2: Box: the median and the middle half.
- Callout 3: Rain: one dot per observation, jittered vertically.
Watch out
- The vertical jitter in the rain carries no meaning; only horizontal position does.
Defaults
- Cloud (half violin)
- On
- Show the smoothed shape of each group.
- Box plot
- On
- Show the median and the middle half of each group.
- Raw points
- On
- Show each observation behind the summary.
- Bandwidth × adjust
- 1
- Multiply the bandwidth: below 1 shows more detail and noise, above 1 gives a smoother curve.
- Range 0.25 to 4, step 0.25
Pinned in the code
- Cloud: Gaussian KDE (bw.nrd0 × adjust) over [min − bw, max + bw], scaled to the tallest group.
- Box: type-7 quartiles, whiskers to the most extreme points within 1.5 × IQR.
- Rain: deterministic seeded vertical jitter (identical across renders and exports).
# Raincloud — Codesplash Chart Lab (recipe "raincloud")
# controls: cloud=true, box=true, points=true, adjust=1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cbook
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("raincloud-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["condition"] = pd.Categorical(df["condition"].astype("string"), categories=["Congruent", "Neutral", "Incongruent"])
def bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
def kde(v, h, grid):
"""Gaussian kernel density by direct summation on `grid` (the app's method)."""
v = np.asarray(v, dtype=float)
grid = np.asarray(grid, dtype=float)
out = np.empty(grid.size)
for i in range(0, grid.size, 32): # chunks keep memory small for large samples
z = (grid[i:i + 32, None] - v[None, :]) / h
out[i:i + 32] = np.exp(-0.5 * z * z).sum(axis=1)
return out / (v.size * h * np.sqrt(2 * np.pi))
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, "rt_ms", "condition", max_levels=8)
k = len(parts)
clouds = []
for label, v in parts:
h = bandwidth(v, "nrd0") * 1
grid = np.linspace(v.min() - h, v.max() + h, 96) # cloud over [min − bw, max + bw]
clouds.append((grid, kde(v, h, grid) if v.size > 1 else np.zeros(96)))
top = max(d.max() for _, d in clouds) or 1.0 # scaled to the tallest group
rng = np.random.default_rng(11) # rain jitter is cosmetic (vertical only); values are never moved
fig, ax = plt.subplots(figsize=(7, 1.2 + 1.2 * k))
for i, ((label, v), (grid, d)) in enumerate(zip(parts, clouds)):
base = k - 1 - i # first group on top
color = PALETTE[i % len(PALETTE)]
ax.fill_between(grid, base, base + 0.45 * d / top, color=color, alpha=0.5, linewidth=0)
# box: type-7 quartiles, whiskers within 1.5 × IQR
ax.bxp([cbook.boxplot_stats(v, whis=1.5)[0]], positions=[base - 0.1], widths=0.08, orientation="horizontal",
showfliers=False, patch_artist=True, boxprops=dict(facecolor=plt.rcParams["axes.facecolor"], edgecolor=plt.rcParams["text.color"]),
medianprops=dict(color=plt.rcParams["text.color"]), manage_ticks=False)
ax.scatter(v, base - 0.27 + rng.uniform(-0.07, 0.07, v.size), s=7, color=color, alpha=0.6, linewidths=0)
ax.set_yticks([k - 1 - i for i in range(k)], [label for label, _ in parts])
ax.grid(axis="y", visible=False)
ax.set_xlabel("rt_ms")
plt.show()Needs pandas, numpy, matplotlib · reads raincloud-demo.csv · app theme from the optional codesplash helper
# Raincloud — Codesplash Chart Lab (recipe "raincloud")
# controls: cloud=true, box=true, points=true, adjust=1
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("raincloud-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["condition"] = pd.Categorical(df["condition"].astype("string"), categories=["Congruent", "Neutral", "Incongruent"])
def bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
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 box_stats(v, k=1.5):
"""Tukey box: type-7 quartiles (np.quantile default), whiskers at the most extreme points within k × IQR."""
q1, med, q3 = np.quantile(v, [0.25, 0.5, 0.75])
iqr = q3 - q1
inside = v[(v >= q1 - k * iqr) & (v <= q3 + k * iqr)]
out = v[(v < q1 - k * iqr) | (v > q3 + k * iqr)]
return dict(q1=q1, med=med, q3=q3, lo=inside.min(), hi=inside.max(), mean=v.mean(),
notch=1.58 * iqr / np.sqrt(v.size), outliers=out)
parts = groups(df, "rt_ms", "condition", max_levels=8)
k = len(parts)
rng = np.random.default_rng(11) # rain jitter is cosmetic; values are never moved
fig = go.Figure()
for i, (label, v) in enumerate(parts):
base = k - 1 - i # first group on top
color = PALETTE[i % len(PALETTE)]
h = bandwidth(v, "nrd0") * 1
# half violin over [min − bw, max + bw]; one scale group keeps one density scale (tallest group)
fig.add_violin(x=v, y=np.full(v.size, base), orientation="h", side="positive", width=0.9, bandwidth=h,
spanmode="manual", span=[v.min() - h, v.max() + h], scalegroup="all", scalemode="width",
points=False, box_visible=False, line_color=color, fillcolor=color, opacity=0.55, name=label, showlegend=False)
s = box_stats(v) # type-7 quartiles, whiskers within 1.5 × IQR (precomputed)
fig.add_box(y=[base - 0.1], q1=[s["q1"]], median=[s["med"]], q3=[s["q3"]], lowerfence=[s["lo"]], upperfence=[s["hi"]],
orientation="h", width=0.08, line_color=color, fillcolor="rgba(0,0,0,0)", showlegend=False)
fig.add_scatter(x=v, y=base - 0.27 + rng.uniform(-0.07, 0.07, v.size), mode="markers", marker=dict(color=color, size=4, opacity=0.6), showlegend=False)
fig.update_layout(violinmode="overlay", xaxis_title="rt_ms", yaxis=dict(tickvals=[k - 1 - i for i in range(k)], ticktext=[label for label, _ in parts], showgrid=False), height=160 + 110 * k)
fig.show()Needs pandas, numpy, plotly · reads raincloud-demo.csv · app theme from the optional codesplash helper
# Raincloud — Codesplash Chart Lab (recipe "raincloud")
# controls: cloud=true, box=true, points=true, adjust=1
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("raincloud-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["condition"]] <- factor(df[["condition"]], levels = c("Congruent", "Neutral", "Incongruent"))
kde <- function(v, h, grid) {
# Gaussian kernel density by direct summation on `grid` (the app's method; density() uses an FFT)
vapply(grid, function(g) sum(dnorm((g - v) / h)), numeric(1)) / (length(v) * h)
}
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]
}
parts <- groups_of(df, "rt_ms", "condition", max_levels = 8)
k <- length(parts)
base <- setNames(k - seq_len(k), names(parts)) # first group on top
clouds <- do.call(rbind, lapply(names(parts), function(lbl) {
v <- parts[[lbl]]
h <- bw.nrd0(v) * 1
grid <- seq(min(v) - h, max(v) + h, length.out = 96) # cloud over [min − bw, max + bw]
data.frame(group = lbl, x = grid, d = if (length(v) > 1) kde(v, h, grid) else 0)
}))
clouds$base <- base[clouds$group]
clouds$top <- clouds$base + 0.45 * clouds$d / max(clouds$d) # scaled to the tallest group
pts <- data.frame(group = rep(names(parts), lengths(parts)), x = unlist(parts, use.names = FALSE))
pts$base <- base[pts$group]
cols <- setNames(rep(cs_cat, length.out = k), names(parts))
p <- ggplot()
p <- p + geom_ribbon(data = clouds, aes(x = x, ymin = base, ymax = top, fill = group), alpha = 0.5, show.legend = FALSE)
p <- p + geom_boxplot(data = pts, aes(x = x, y = base - 0.1, group = group), orientation = "y", width = 0.08, coef = 1.5, outlier.shape = NA, fill = NA) # type 7
p <- p + geom_point(data = pts, aes(x = x, y = base - 0.27, colour = group), position = position_jitter(width = 0, height = 0.07, seed = 11), size = 0.8, alpha = 0.6, show.legend = FALSE)
p <- p + scale_fill_manual(values = cols) + scale_colour_manual(values = cols) +
scale_y_continuous(breaks = base, labels = names(base)) +
labs(x = "rt_ms", y = NULL) + theme_cs + theme(panel.grid.major.y = element_blank())
print(p)Needs ggplot2 · reads raincloud-demo.csv · app theme from the optional codesplashr helper
-- Raincloud — Codesplash Chart Lab (recipe "raincloud")
-- controls: cloud=true, box=true, points=true, adjust=1
-- Tukey box statistics: type-7 quartiles (quantile_cont), whiskers at the most extreme values
-- within 1.5 × IQR of the box, notch half-width 1.58·IQR/√n (McGill, Tukey & Larsen 1978)
WITH v0 AS (
SELECT "condition"::VARCHAR AS grp, "rt_ms"::DOUBLE AS x
FROM read_csv('raincloud-demo.csv')
WHERE "rt_ms" IS NOT NULL AND isfinite("rt_ms"::DOUBLE) AND "condition" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 8 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['Congruent', 'Neutral', 'Incongruent'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 8),
q AS (
SELECT grp, rk, count(*) AS n, avg(x) AS mean,
quantile_cont(x, 0.25) AS q1, quantile_cont(x, 0.5) AS median, quantile_cont(x, 0.75) AS q3,
min(x) AS vmin, max(x) AS vmax
FROM v
GROUP BY grp, rk
)
SELECT q.grp AS "group", q.n, q.vmin AS min, q.q1, q.median, q.q3, q.vmax AS max, q.mean,
min(v.x) FILTER (WHERE v.x >= q.q1 - 1.5 * (q.q3 - q.q1)) AS whisker_lo,
max(v.x) FILTER (WHERE v.x <= q.q3 + 1.5 * (q.q3 - q.q1)) AS whisker_hi,
count(*) FILTER (WHERE v.x < q.q1 - 1.5 * (q.q3 - q.q1) OR v.x > q.q3 + 1.5 * (q.q3 - q.q1)) AS outliers,
1.58 * (q.q3 - q.q1) / sqrt(q.n) AS notch_half_width
FROM q JOIN v USING (grp)
GROUP BY q.grp, q.rk, q.n, q.vmin, q.q1, q.median, q.q3, q.vmax, q.mean
ORDER BY q.rk;Needs duckdb · reads raincloud-demo.csv
- Rain jitter is drawn from a seeded generator in each language, so dot positions differ from the app; values (and every box and cloud) are identical.