雨云图

按组横向绘制半边小提琴图、箱线图和原始数据点。

雨云图

雨云图将同一数据的三种视图叠在一起:半边小提琴图(“云”)展示密度,细长的箱线图给出中位数和四分位数,下方抖动的散点(“雨”)则呈现每一个观测值。没有任何信息被隐藏,因此偏态、离群值和小样本都一目了然。

本例的背景是 de Marcellis-Warin、Kouloukoui 与 Warin(2025,Data in Brief)发布的人工智能相关推文大规模数据集。此处的数字为说明而模拟——四个 AI 话题下 n = 480 条推文的情感得分,取值从 −1(负面)到 +1(正面)——并非论文的数据或结果。密度由 scipy.stats.gaussian_kde 计算,副标题报告 Kruskal–Wallis 检验(scipy.stats.kruskal)——一种适用于有界、偏态得分的秩检验——并以 ε² 作为效应量。

代码及图中文字均为英文。

raincloud.py · 48 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Simulated data, set in the context of de Marcellis-Warin, Kouloukoui & Warin (2025) [dmw2025aitweets]

# Data: sentiment score (−1 to +1) of 120 tweets per AI topic (Beta draws rescaled)
rng = np.random.default_rng(2025)
groups = {"AI in healthcare": (5.0, 3.5), "Generative AI tools": (4.0, 3.5),
          "AI regulation": (3.5, 4.0), "AI and jobs": (2.6, 4.5)}
data = [2 * rng.beta(a, b, 120) - 1 for a, b in groups.values()]
palette = ["#007AFF", "#FF9500", "#34C759", "#FF3B30"]

# Kruskal–Wallis test + epsilon squared
H, p = stats.kruskal(*data)
n = sum(len(d) for d in data)
eps2 = H / (n - 1)

fig, ax = plt.subplots(figsize=(8, 5.6))
for i, (d, c) in enumerate(zip(data, palette)):
    # Cloud: half violin above the baseline, scaled to a fixed height
    grid = np.linspace(d.min() - 0.05, d.max() + 0.05, 300)  # trim the cloud near the data
    dens = stats.gaussian_kde(d)(grid)
    ax.fill_between(grid, i, i + 0.55 * dens / dens.max(), color=c, alpha=0.3, lw=0)
    ax.plot(grid, i + 0.55 * dens / dens.max(), color=c, lw=1.4)
    # Box: median and quartiles just under the cloud
    ax.boxplot(d, positions=[i - 0.1], widths=0.09, orientation="horizontal", showfliers=False,
               patch_artist=True, boxprops=dict(facecolor="white", edgecolor="#3A3A3C", lw=1),
               medianprops=dict(color=c, lw=2.2), whiskerprops=dict(color="#3A3A3C"),
               capprops=dict(visible=False))
    # Rain: jittered raw points below the box
    ax.scatter(d, i - 0.3 + rng.uniform(-0.08, 0.08, len(d)),
               s=12, color=c, alpha=0.55, lw=0)

ax.set_yticks(range(len(groups)), [f"{g}\nmedian {np.median(d):+.2f} · n = {len(d)}"
                                   for g, d in zip(groups, data)])
ax.set_ylim(-0.5, len(groups) - 0.3)
ax.set_xlim(-1, 1)
ax.axvline(0, color="#8E8E93", lw=0.8, ls="--", zorder=0)
ax.grid(axis="x"); ax.grid(axis="y", visible=False)
ax.set_xlabel("Tweet sentiment score (−1 = negative, +1 = positive)")
share = [np.mean(d < 0) for d in data]
ax.set_title(f"{share[3]:.0%} of tweets on AI and jobs are negative, "
             f"{share[0]:.0%} of those on AI in healthcare", pad=26)
ax.text(0, 1.02, f"n = {n} tweets (simulated) · Kruskal–Wallis H(3) = {H:.1f}, p = {p:.1e}, "
        f"ε² = {eps2:.2f} · box = quartiles, rain = tweets", transform=ax.transAxes,
        fontsize=9.5, color="#6E6E73")
plt.show()

图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。

数据来源

  • Simulated data. Simulated data with a fixed random seed, created for this example.
    No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work.
  • de Marcellis-Warin, Kouloukoui & Warin (2025), AI-related tweets. de Marcellis-Warin, N., Kouloukoui, D., & Warin, T. (2025). A large-scale dataset of AI-related tweets: Structure and descriptive statistics. Data in Brief, 62, 111960. https://doi.org/10.1016/j.dib.2025.111960
    The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.

这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。

如何引用

PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。

Warin, T. (2026). Raincloud plot. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/distributions/raincloud/

@misc{warin2026statlas,
  author       = {Warin, Thierry},
  title        = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
  year         = {2026},
  version      = {1.1.0},
  howpublished = {\url{https://warin.ca/pystatlas/}},
  note         = {Source code: https://github.com/warint/pystatlas}
}

更多分布图表