密度曲線付きヒストグラム
ヒストグラム、カーネル密度、当てはめた正規曲線を、分布の形状を表す統計量とともに示します。

連続変数を調べるときに最初に見るべきグラフです。棒は密度スケールで経験分布を表し、実線はカーネル密度推定(KDE)、破線は同じ平均と標準偏差をもつ正規分布です。2本の曲線が食い違う場合、データは正規分布に従っていません。ここでは0から1の範囲に収まる類似度指数がゼロ付近に集まり、右に長く伸びた裾が 平均 を 中央値 より大きく引き上げています。
舞台は Sanger & Warin(2019、Data in Brief)による、ヨーロッパの政党マニフェスト間のジャッカード類似度指数のデータセットです。ここでの数値は説明のために シミュレーション したもの(ベータ分布、マニフェストの組 n = 600)であり、論文のデータや結果ではありません。scipy.stats.gaussian_kde で密度を描き、scipy.stats.skew / kurtosis で形状を記述し、scipy.stats.shapiro で正規性を検定しています。
コードおよび図中のテキストは英語です。
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()
# Histogram with density: the R equivalent of plot.py
# Simulated data, set in the context of Sanger & Warin (2019) [sanger2019]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2019)
# Data: Jaccard similarity (0 = no shared words, 1 = identical) of 600 manifesto pairs
x <- rbeta(600, 1.6, 7.5)
n <- length(x)
m <- mean(x)
med <- median(x)
s <- sd(x)
# Shape statistics and normality test
dev <- x - m
skew <- mean(dev^3) / mean(dev^2)^1.5
kurt <- mean(dev^4) / mean(dev^2)^2 - 3 # excess kurtosis, 0 for a normal
sw <- shapiro.test(x)
# Mean and median markers, labelled on either side of their line
marks <- data.frame(value = c(m, med), name = c("Mean", "Median"), hjust = c(-0.15, 1.15))
marks$label <- sprintf("%s\n%.3f", marks$name, marks$value)
p <- ggplot(data.frame(x = x), aes(x)) +
geom_histogram(aes(y = after_stat(density)), bins = 30, boundary = 0,
fill = "#007AFF", alpha = 0.25, colour = "white") +
# Kernel density estimate and the normal curve with the same mean / SD
geom_density(aes(colour = "Kernel density", linetype = "Kernel density"), linewidth = 1,
key_glyph = "path") +
stat_function(aes(colour = "Normal fit (same mean, SD)", linetype = "Normal fit (same mean, SD)"),
fun = dnorm, args = list(mean = m, sd = s), linewidth = 0.7) +
scale_colour_manual(NULL, values = c("Kernel density" = "#007AFF",
"Normal fit (same mean, SD)" = "#8E8E93")) +
scale_linetype_manual(NULL, values = c("Kernel density" = "solid",
"Normal fit (same mean, SD)" = "dashed")) +
geom_vline(data = marks, aes(xintercept = value), colour = c("#FF9500", "#34C759"),
linewidth = 0.7) +
geom_text(data = marks, aes(x = value, y = Inf, label = label, hjust = hjust), vjust = 1.2,
colour = c("#FF9500", "#34C759"), fontface = "bold", size = 3.3, lineheight = 0.95) +
scale_x_continuous(limits = c(0, 0.7), expand = c(0, 0)) +
scale_y_continuous(expand = expansion(mult = c(0, 0.18))) + # headroom for the labels
labs(title = sprintf("Most manifesto pairs share little vocabulary: median Jaccard %.2f, %d pairs above 0.4",
med, sum(x > 0.4)),
subtitle = sprintf(paste("n = %d manifesto pairs (simulated) · skewness = %.2f ·",
"excess kurtosis = %.2f · Shapiro–Wilk W = %.3f, p = %.1e"),
n, skew, kurt, unname(sw$statistic), sw$p.value),
x = "Jaccard similarity between two party manifestos", y = "Density") +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold", size = 11.5),
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
axis.text.y = element_blank(),
panel.grid.minor = element_blank(), panel.grid.major.y = element_blank(),
legend.position = "inside", legend.position.inside = c(0.98, 0.72),
legend.justification = c(1, 1))
print(p)
図にはオプションの 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}
}