带密度曲线的直方图

直方图、核密度和拟合的正态曲线,并附形态统计量。

带密度曲线的直方图

这是审视任何连续变量的第一步。柱形以密度刻度展示经验分布,实线是核密度估计(KDE),虚线是均值和标准差相同的正态分布。两条曲线不一致时,说明数据并非正态——此处一个取值介于 0 和 1 之间的相似度指数堆积在零附近,其长长的右尾把均值拉到了中位数之上。

本例的背景是 Sanger 与 Warin(2019,Data in Brief)发布的欧洲政党竞选纲领之间 Jaccard 相似度指数数据集。此处的数字为说明而模拟(Beta 分布,n = 600 对纲领),并非论文的数据或结果。scipy.stats.gaussian_kde 绘制密度,scipy.stats.skew / kurtosis 描述形态,scipy.stats.shapiro 检验正态性。

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

histogram-density.py · 45 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Simulated data, set in the context of Sanger & Warin (2019) [sanger2019]

# Data: Jaccard similarity (0 = no shared words, 1 = identical) of 600 manifesto pairs
rng = np.random.default_rng(2019)
x = rng.beta(1.6, 7.5, size=600)
mean, median, sd = x.mean(), np.median(x), x.std(ddof=1)

# Shape statistics and normality test
skew, kurt = stats.skew(x), stats.kurtosis(x)  # kurtosis: excess, 0 for a normal
W, p = stats.shapiro(x)

fig, ax = plt.subplots(figsize=(8, 5))
ax.hist(x, bins=30, density=True, color="#007AFF", alpha=0.25, edgecolor="white")

# Kernel density estimate and the normal curve with the same mean / SD
grid = np.linspace(0, 0.7, 400)
ax.plot(grid, stats.gaussian_kde(x)(grid), color="#007AFF", lw=2.2, label="Kernel density")
ax.plot(grid, stats.norm.pdf(grid, mean, sd), color="#8E8E93", lw=1.6, ls="--",
        label="Normal fit (same mean, SD)")

# Mean and median markers
ymax = ax.get_ylim()[1] * 1.18  # headroom above the bars for the labels
ax.set_ylim(0, ymax)
for value, name, color, ha, dx in [(mean, "Mean", "#FF9500", "left", 6),
                                   (median, "Median", "#34C759", "right", -6)]:
    ax.axvline(value, color=color, lw=1.6, ymax=0.97)
    ax.annotate(f"{name}\n{value:.3f}", (value, ymax * 0.97), xytext=(dx, -2),
                textcoords="offset points", ha=ha, va="top", fontsize=9.5,
                fontweight="semibold", color=color)

ax.set_xlim(0, grid[-1])
ax.set_yticks([])
ax.set_ylabel("Density")
ax.set_xlabel("Jaccard similarity between two party manifestos")
ax.legend(loc="upper right")
ax.set_title(f"Most manifesto pairs share little vocabulary: median Jaccard {median:.2f}, "
             f"{(x > 0.4).sum()} pairs above 0.4", pad=26)
ax.text(0, 1.02, f"n = {len(x)} manifesto pairs (simulated) · skewness = {skew:.2f} · "
        f"excess kurtosis = {kurt:.2f} · Shapiro–Wilk W = {W:.3f}, p = {p:.1e}",
        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.
  • Sanger & Warin (2019), similarity of European party manifestos. Sanger, W., & Warin, T. (2019). Dataset of Jaccard similarity indices from 1,597 European political manifestos across 27 countries (1945–2017). Data in Brief, 24, 103907. https://doi.org/10.1016/j.dib.2019.103907
    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). Histogram with density. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/distributions/histogram-density/

@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}
}

更多分布图表