Skip to content
svgbrushableraincloud

Raincloud

How do groups compare in shape, summary and individual observations at once?

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

How to read it

  1. Read the cloud for each group's shape.
  2. Read the box for its median and middle half.
  3. Read the rain to check the summaries against the real observations and spot gaps or clumps.
  1. Callout 1: Cloud: the shape of the distribution.
  2. Callout 2: Box: the median and the middle half.
  3. 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

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