附相关系数的配对图
四个地区增长变量的散点图矩阵,对角线为分组密度,上方为合并相关与组内相关。

GGally::ggpairs() 的 Python 版本。对角线以下,每对变量都有一张按组着色的散点图;对角线展示每个变量在各组中的密度;对角线以上的对称单元格则给出 Pearson r,包括总体(粗体)和各组内的值,并附显著性星号。比较二者正是关键:当各组位于图中不同区域时,合并相关与组内相关可能差异悬殊——甚至符号相反。
背景设定为 Hadengue 与 Warin(2014,Management international)关于巴西、中国和印度的专业化与(无)条件收敛的研究。数据为用于说明的模拟数据,并非论文的数据或结果:86 个地区(巴西 27 个州、中国 31 个省、印度 28 个邦),包括平均增长率、初始人均收入的对数、专业化指数和出口多样化指数。在每个国家内部,较穷的地区增长更快(条件收敛),而合并相关则混入了国家之间的差距。密度使用 scipy.stats.gaussian_kde,相关系数使用 scipy.stats.pearsonr;网格是一个普通的 plt.subplots(4, 4)。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
# Simulated data, set in the context of Hadengue & Warin (2014) [hadengue2014]
# Simulated regions: country means differ; within a country, poorer regions grow faster
rng = np.random.default_rng(2014)
groups = ["Brazil", "China", "India"]
setup = {"Brazil": (27, 9.2, 2.5), "China": (31, 9.0, 9.0), "India": (28, 7.4, 6.0)}
parts = []
for g, (n, inc0, gr0) in setup.items():
dev = rng.normal(0, 0.45, n) # region's income gap to its country mean
spec = 0.30 - 0.12 * dev + rng.normal(0, 0.05, n)
parts.append(pd.DataFrame({"Growth (% per yr)": gr0 - 2.2 * dev + rng.normal(0, 0.7, n),
"Initial income (log)": inc0 + dev,
"Specialisation index": spec,
"Export diversification": 3.4 - 4 * spec + rng.normal(0, 0.25, n),
"group": g}))
df = pd.concat(parts, ignore_index=True)
cols = df.columns[:4]
palette = ["#007AFF", "#FF9500", "#34C759"]
stars = lambda p: "***" if p < .001 else "**" if p < .01 else "*" if p < .05 else ""
fig, axes = plt.subplots(4, 4, figsize=(9.5, 8.6), sharex="col", layout="constrained")
lims = {c: (df[c].min() - 0.05 * np.ptp(df[c]), df[c].max() + 0.05 * np.ptp(df[c])) for c in cols}
fig.get_layout_engine().set(rect=(0, 0, 1, 0.92), w_pad=0.04, h_pad=0.04)
for i, yv in enumerate(cols):
for j, xv in enumerate(cols):
ax = axes[i, j]
ax.grid(False)
if i == j: # diagonal: KDE per group
grid = np.linspace(*lims[xv], 200)
for s, c in zip(groups, palette):
dens = stats.gaussian_kde(df.loc[df.group == s, xv])(grid)
ax.fill_between(grid, dens, color=c, alpha=0.25, lw=0)
ax.plot(grid, dens, color=c, lw=1.3)
ax.set_yticks([])
elif i > j: # lower: scatter by group
for s, c in zip(groups, palette):
d = df[df.group == s]
ax.scatter(d[xv], d[yv], s=12, color=c, alpha=0.65, lw=0)
ax.set_ylim(lims[yv])
else: # upper: correlation coefficients
r, p = stats.pearsonr(df[xv], df[yv])
ax.text(0.5, 0.78, f"r = {r:.2f}{stars(p)}", ha="center", fontsize=11,
fontweight="semibold", transform=ax.transAxes)
for k, (s, c) in enumerate(zip(groups, palette)):
d = df[df.group == s]
rs, ps = stats.pearsonr(d[xv], d[yv])
ax.text(0.5, 0.52 - k * 0.17, f"{s}: {rs:.2f}{stars(ps)}", ha="center",
fontsize=9, color=c, transform=ax.transAxes)
ax.tick_params(labelbottom=False, labelleft=False)
for sp in ax.spines.values():
sp.set_visible(False)
if i < 3:
ax.tick_params(labelbottom=False)
if j > 0 or i == 0:
ax.tick_params(labelleft=False)
if i == 3:
ax.set_xlabel(xv)
ax.set_xlim(lims[xv])
if j == 0:
ax.set_ylabel(yv)
fig.text(0.01, 0.985, "Within each country, poorer regions grow faster", fontsize=13,
fontweight="semibold", va="top")
fig.text(0.01, 0.945, f"Pearson r, overall (bold) and within country · n = {len(df)} regions "
"(simulated) · * p<.05 ** p<.01 *** p<.001", fontsize=9.5, color="#6E6E73", va="top")
plt.show()
# Pairs plot with correlations: the R equivalent of plot.py
# Simulated data, set in the context of Hadengue & Warin (2014) [hadengue2014]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2014)
# Simulated regions: country means differ; within a country, poorer regions grow faster
groups <- c("Brazil", "China", "India")
setup <- list(Brazil = c(27, 9.2, 2.5), China = c(31, 9.0, 9.0), India = c(28, 7.4, 6.0))
df <- do.call(rbind, lapply(groups, function(g) {
n <- setup[[g]][1]; inc0 <- setup[[g]][2]; gr0 <- setup[[g]][3]
dev <- rnorm(n, 0, 0.45) # region's income gap to its country mean
spec <- 0.30 - 0.12 * dev + rnorm(n, 0, 0.05)
data.frame("Growth (% per yr)" = gr0 - 2.2 * dev + rnorm(n, 0, 0.7),
"Initial income (log)" = inc0 + dev,
"Specialisation index" = spec,
"Export diversification" = 3.4 - 4 * spec + rnorm(n, 0, 0.25),
group = g, check.names = FALSE)
}))
cols <- names(df)[1:4]
palette <- c(Brazil = "#007AFF", China = "#FF9500", India = "#34C759")
stars <- function(p) ifelse(p < .001, "***", ifelse(p < .01, "**", ifelse(p < .05, "*", "")))
lims <- lapply(df[cols], function(v) range(v) + c(-0.05, 0.05) * diff(range(v)))
# GGally is not installed: one facet_grid with free scales, a panel per (row = y, column = x) pair
panel <- function(yv, xv, d) cbind(d, yvar = factor(yv, cols), xvar = factor(xv, cols))
pts <- dens <- txt <- frame <- list()
for (i in seq_along(cols)) for (j in seq_along(cols)) {
yv <- cols[i]; xv <- cols[j]
# invisible corners fix every panel to the variables' padded ranges
frame[[length(frame) + 1]] <- panel(yv, xv, data.frame(x = lims[[xv]], y = lims[[yv]]))
if (i == j) { # diagonal: density per group, scaled to the row's range
grid <- seq(lims[[xv]][1], lims[[xv]][2], length.out = 200)
dd <- do.call(rbind, lapply(groups, function(s) {
k <- density(df[df$group == s, xv], from = lims[[xv]][1], to = lims[[xv]][2], n = 200)
data.frame(x = k$x, dens = k$y, group = s)
}))
dd$ymin <- lims[[yv]][1]
dd$y <- lims[[yv]][1] + 0.92 * dd$dens / max(dd$dens) * diff(lims[[yv]])
dens[[length(dens) + 1]] <- panel(yv, xv, dd)
} else if (i > j) { # lower: scatter by group
pts[[length(pts) + 1]] <- panel(yv, xv, data.frame(x = df[[xv]], y = df[[yv]], group = df$group))
} else { # upper: correlation coefficients
ct <- cor.test(df[[xv]], df[[yv]])
rows <- data.frame(label = sprintf("r = %.2f%s", ct$estimate, stars(ct$p.value)), group = "all",
pos = 0.78, size = 3.9, face = "bold")
for (k in seq_along(groups)) {
s <- groups[k]
cs <- cor.test(df[df$group == s, xv], df[df$group == s, yv])
rows <- rbind(rows, data.frame(label = sprintf("%s: %.2f%s", s, cs$estimate, stars(cs$p.value)),
group = s, pos = 0.52 - (k - 1) * 0.17, size = 3.2, face = "plain"))
}
rows$x <- mean(lims[[xv]])
rows$y <- lims[[yv]][1] + rows$pos * diff(lims[[yv]])
txt[[length(txt) + 1]] <- panel(yv, xv, rows)
}
}
pts <- do.call(rbind, pts); dens <- do.call(rbind, dens)
txt <- do.call(rbind, txt); frame <- do.call(rbind, frame)
p <- ggplot(mapping = aes(x, y)) +
geom_blank(data = frame) +
geom_ribbon(data = dens, aes(ymin = ymin, ymax = y, fill = group), alpha = 0.25) +
geom_line(data = dens, aes(colour = group), linewidth = 0.6) +
geom_point(data = pts, aes(colour = group), size = 1.3, alpha = 0.65, stroke = 0) +
geom_text(data = txt, aes(label = label, colour = group, size = size, fontface = face)) +
scale_size_identity() +
scale_colour_manual(values = c(palette, all = "#1D1D1F"), breaks = groups, name = NULL) +
scale_fill_manual(values = palette, guide = "none") +
facet_grid(yvar ~ xvar, scales = "free", switch = "both") +
scale_x_continuous(n.breaks = 4) +
scale_y_continuous(n.breaks = 4) +
labs(title = "Within each country, poorer regions grow faster",
subtitle = sprintf("Pearson r, overall (bold) and within country · n = %d regions (simulated) · * p<.05 ** p<.01 *** p<.001",
nrow(df)),
x = NULL, y = NULL) +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
panel.grid = element_blank(),
panel.border = element_rect(fill = NA, colour = "#D1D1D6", linewidth = 0.4),
panel.spacing = unit(0.5, "lines"),
strip.placement = "outside",
strip.text = element_text(size = 9.5, colour = "#1D1D1F"),
axis.text = element_text(size = 7.5, colour = "#6E6E73"),
legend.position = "top", legend.justification = "left",
legend.margin = margin(0, 0, 0, 0)) +
guides(colour = guide_legend(override.aes = list(size = 2.5, alpha = 1, linewidth = 0, label = "")))
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. - Hadengue & Warin (2014), specialisation and convergence in Brazil, China and India. Hadengue, M., & Warin, T. (2014). Patterns of specialization and (un)conditional convergence: The cases of Brazil, China and India. Management international, 18, 123–141. https://doi.org/10.7202/1027869ar
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). Pairs plot with correlations. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/correlation/pairs-plot/
@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}
}