How to Make a Raincloud Plot in Python

Build raincloud plots in Matplotlib from a half violin, a box plot, and jittered points, or use the ptitprince package.

A raincloud plot shows a distribution three ways at once: a half violin (the cloud), a box plot, and the raw points (the rain). To make one in Python, draw ax.violinplot() with side="low" or side="high", add a narrow ax.boxplot(), and scatter jittered points beside it.

The code below needs Matplotlib 3.10 or newer. The side argument arrived in 3.9 and orientation in 3.10.

Quick Example

This horizontal raincloud plot compares reaction times under three conditions, using simulated data.

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(17)
groups = {
    "Rested": rng.normal(265, 28, 140),
    "Caffeine": rng.normal(245, 24, 140),
    "Sleep deprived": np.concatenate([rng.normal(285, 22, 80),
                                      rng.normal(385, 28, 60)]),
}
colors = ["#2a9d8f", "#e9a23b", "#9c4f96"]

fig, ax = plt.subplots(figsize=(9, 6))

for pos, (values, color) in enumerate(zip(groups.values(), colors)):
    # cloud: half a violin, drawn upward because the y-axis is inverted below
    cloud = ax.violinplot(values, positions=[pos], orientation="horizontal",
                          side="low", widths=0.8, showextrema=False)
    cloud["bodies"][0].set(facecolor=color, alpha=0.7)

    # box plot just under the cloud
    ax.boxplot(values, positions=[pos + 0.08], orientation="horizontal",
               widths=0.1, showfliers=False, patch_artist=True,
               boxprops={"facecolor": "white"}, medianprops={"color": "black"},
               manage_ticks=False)

    # rain: jittered points below
    jitter = rng.uniform(-0.1, 0.1, len(values))
    ax.scatter(values, pos + 0.28 + jitter, s=9, color=color, alpha=0.6,
               linewidths=0)

ax.set_yticks(range(len(groups)), list(groups))
ax.invert_yaxis()
ax.set_xlabel("Reaction time (ms)")
ax.set_title("Reaction times under three conditions", loc="left")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()

Horizontal raincloud plot of reaction times. Rested and Caffeine have single peaks, while Sleep deprived has two clusters near 285 and 390 milliseconds

The details that make it work:

  • side keeps half of the violin. On an inverted y-axis, "low" appears above the position.
  • manage_ticks=False stops boxplot() from replacing your tick positions.
  • showfliers=False hides the box plot's outlier markers, since every point is already in the rain.
  • Jitter spreads points across the category axis only, so their values stay exact.

Raincloud Plot vs Box Plot vs Violin Plot

data = list(groups.values())

fig, axes = plt.subplots(1, 3, figsize=(11, 4), sharey=True)
axes[0].boxplot(data, tick_labels=list(groups))
axes[0].set_title("Box plot")
axes[1].violinplot(data, showmedians=True)
axes[1].set_title("Violin plot")
for pos, (values, color) in enumerate(zip(data, colors), 1):
    half = axes[2].violinplot(values, positions=[pos], side="high", widths=0.8,
                              showextrema=False)
    half["bodies"][0].set(facecolor=color, alpha=0.7)
    x = pos - 0.22 + rng.uniform(-0.12, 0.12, len(values))
    axes[2].scatter(x, values, s=6, color=color, alpha=0.6, linewidths=0)
axes[2].set_title("Raincloud (no box)")
for ax in axes:
    ax.set_xticks([1, 2, 3], ["Rested", "Caffeine", "Sleep\ndeprived"])
    ax.spines[["top", "right"]].set_visible(False)
axes[0].set_ylabel("Reaction time (ms)")
fig.tight_layout()
plt.show()

The same data as a box plot, a violin plot and a half violin with points. The box plot hides the two clusters in the sleep deprived group

The sleep deprived box runs from 280 to 386 ms with a median of 304, and gives no hint that few people fall in the middle of that range. The violin and the points both show two groups.

Chart Shows Weakness
Box plot Median, quartiles, outliers Hides multiple peaks
Violin plot Smoothed density Hides sample size
Raincloud plot Density, summary, and every point Needs more space, and the rain gets crowded with large samples

A Reusable Vertical Raincloud Function

Wrapping the three layers in a function makes the chart a one-liner:

def raincloud(ax, data, colors, bw_method=None, seed=0):
    """Draw one vertical raincloud per array in data, at positions 0, 1, 2..."""
    rng = np.random.default_rng(seed)
    for pos, (values, color) in enumerate(zip(data, colors)):
        cloud = ax.violinplot(values, positions=[pos], side="high", widths=0.8,
                              showextrema=False, bw_method=bw_method)
        cloud["bodies"][0].set(facecolor=color, alpha=0.7)
        ax.boxplot(values, positions=[pos - 0.07], widths=0.09, showfliers=False,
                   patch_artist=True, boxprops={"facecolor": "white"},
                   medianprops={"color": "black"}, manage_ticks=False)
        x = pos - 0.27 + rng.uniform(-0.09, 0.09, len(values))
        ax.scatter(x, values, s=8, color=color, alpha=0.6, linewidths=0)


rng = np.random.default_rng(23)
salaries = [rng.lognormal(np.log(median), spread, size)
            for median, spread, size in [(68, 0.18, 120), (92, 0.22, 200),
                                         (118, 0.30, 90), (135, 0.16, 40)]]
levels = ["Junior", "Mid", "Senior", "Lead"]

fig, ax = plt.subplots(figsize=(9, 5.5))
raincloud(ax, salaries, ["#577590", "#43aa8b", "#f8961e", "#f94144"])
ax.set_xticks(range(4), [f"{name}\n(n={len(v)})" for name, v in zip(levels, salaries)])
ax.set_ylabel("Salary (thousands of US$)")
ax.set_title("Salary by level", loc="left")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()

Vertical raincloud plot of simulated salaries for four levels, with medians rising from about 65 thousand for Junior to 142 thousand for Lead

Add the sample size to each label. A smooth cloud built from 40 points looks as solid as one built from 200.

Adjust the Cloud's Bandwidth

bw_method controls how smooth the density estimate is. A small number follows the data closely, and a large one smooths real features away.

fig, axes = plt.subplots(1, 3, figsize=(11, 3.6), sharey=True)
for ax, bw in zip(axes, [0.08, None, 0.8]):
    raincloud(ax, [groups["Sleep deprived"]], ["#9c4f96"], bw_method=bw)
    ax.set_title(f"bw_method={bw}")
    ax.set_xticks([])
    ax.spines[["top", "right"]].set_visible(False)
axes[0].set_ylabel("Reaction time (ms)")
fig.tight_layout()
plt.show()

Three bandwidths for one raincloud: 0.08 is jagged, the default shows two peaks, and 0.8 merges them into one

The default (None, Scott's rule) shows the two peaks. At 0.8 they disappear.

Raincloud Plots with ptitprince

The ptitprince package draws all three layers from a long-format DataFrame. Install it with pip install ptitprince.

import pandas as pd
import ptitprince as pt

df = pd.DataFrame(
    [(name, v) for name, values in groups.items() for v in values],
    columns=["condition", "ms"],
)

np.random.seed(0)  # the point jitter uses NumPy's global random state
fig, ax = plt.subplots(figsize=(9, 6))
pt.RainCloud(data=df, x="condition", y="ms", orient="h", palette=colors,
             bw=0.2, width_viol=0.7, move=0.2, ax=ax)
ax.set_xlabel("Reaction time (ms)")
ax.set_ylabel("")
ax.set_title("The same data with ptitprince", loc="left")
fig.tight_layout()
plt.show()

Raincloud plot drawn by ptitprince with clouds above, box plots in the middle and points below for each condition

x is the category and y the value, even when orient="h" makes the chart horizontal. move shifts the points away from the box.

With ptitprince 0.3.1, Seaborn 0.13.2, and Matplotlib 3.11, this call emits deprecation warnings for palette without hue and for Matplotlib's vert argument. It draws correctly today, but a later Seaborn or Matplotlib release could break it. The Matplotlib version above doesn't have that dependency.

Similar Topics