Scatterplot with statistics
Trade intensity vs business-cycle correlation for country pairs — scatter, OLS line with 95% band, marginal histograms and Pearson's r.

The Python counterpart of ggscatterstats(). The central panel shows every
observation with the least-squares line and its 95% confidence band (uncertainty
about the mean of y at each x, not about individual points). Marginal
histograms on the top and right reveal the shape of each variable, which a
correlation coefficient silently assumes is reasonable. The subtitle reports
Pearson's r with its 95% confidence interval, the t-test, the OLS slope and
the sample size.
The setting is Janicki, Warin & Wunnava (2009, Review of International
Economics), which tests Mundell's intuition that trade integration makes
business cycles move together. The data are simulated for illustration and
are not the paper's data or results: 190 country pairs (all pairs of 20
countries), with the log of bilateral trade intensity and the correlation of the
two countries' detrended output. The fitted line describes an association between
pairs, not an effect. The test comes from scipy.stats.pearsonr, the line and
band from statsmodels OLS get_prediction().conf_int().
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
from scipy import stats
# Simulated data, set in the context of Janicki, Warin & Wunnava (2009) [janicki2009]
# Simulated country pairs: 20 countries -> 190 pairs; cycles co-move more where trade is denser
rng = np.random.default_rng(2009)
x = rng.normal(-5.5, 1.1, 190) # log(bilateral trade / combined GDP)
y = np.tanh(0.35 + 0.13 * (x + 5.5) + rng.normal(0, 0.28, 190)) # business-cycle correlation
n = len(x)
# Pearson correlation with its 95% CI
res = stats.pearsonr(x, y)
ci = res.confidence_interval(0.95)
# OLS fit and 95% confidence band for the mean
fit = sm.OLS(y, sm.add_constant(x)).fit()
grid = np.linspace(x.min(), x.max(), 200)
band = fit.get_prediction(sm.add_constant(grid)).conf_int(alpha=0.05)
fig = plt.figure(figsize=(8, 6.4))
gs = fig.add_gridspec(2, 2, width_ratios=(5, 1), height_ratios=(1, 5), wspace=0.03, hspace=0.03)
ax = fig.add_subplot(gs[1, 0])
ax_top = fig.add_subplot(gs[0, 0], sharex=ax)
ax_right = fig.add_subplot(gs[1, 1], sharey=ax)
ax.scatter(x, y, s=22, color="#007AFF", alpha=0.45, lw=0)
ax.fill_between(grid, band[:, 0], band[:, 1], color="#FF9500", alpha=0.25, lw=0)
ax.plot(grid, fit.params[0] + fit.params[1] * grid, color="#FF9500", lw=2.2)
ax.set_xlabel("Bilateral trade intensity (log of trade / combined GDP)")
ax.set_ylabel("Business-cycle correlation")
ax.grid(axis="x")
# Marginal histograms
ax_top.hist(x, bins=30, color="#007AFF", alpha=0.35, edgecolor="white")
ax_right.hist(y, bins=30, color="#007AFF", alpha=0.35, edgecolor="white", orientation="horizontal")
for a in (ax_top, ax_right):
a.axis("off")
ax_top.set_title("Pairs that trade more have more synchronised business cycles", pad=26)
p_txt = "p < .001" if res.pvalue < 0.001 else f"p = {res.pvalue:.3f}"
ax_top.text(0, 1.06, f"Pearson r = {res.statistic:.2f}, 95% CI [{ci.low:.2f}, {ci.high:.2f}], "
f"t({n - 2}) = {fit.tvalues[1]:.1f}, {p_txt} · slope = {fit.params[1]:.2f} · n = {n} pairs (simulated)",
transform=ax_top.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
# Scatterplot with statistics: the R equivalent of plot.py
# Simulated data, set in the context of Janicki, Warin & Wunnava (2009) [janicki2009]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2009)
# Simulated country pairs: 20 countries -> 190 pairs; cycles co-move more where trade is denser
x <- rnorm(190, -5.5, 1.1) # log(bilateral trade / combined GDP)
y <- tanh(0.35 + 0.13 * (x + 5.5) + rnorm(190, 0, 0.28)) # business-cycle correlation
n <- length(x)
d <- data.frame(x, y)
# Pearson correlation with its 95% CI
ct <- cor.test(x, y)
# OLS fit and 95% confidence band for the mean
fit <- lm(y ~ x, data = d)
grid <- data.frame(x = seq(min(x), max(x), length.out = 200))
grid <- cbind(grid, predict(fit, grid, interval = "confidence"))
# Marginal histograms, drawn in strips above (x) and to the right (y) of the scatter
xr <- range(x); yr <- range(y)
top <- yr[2] + 0.06 * diff(yr); top_h <- 0.22 * diff(yr)
right <- xr[2] + 0.04 * diff(xr); right_w <- 0.2 * diff(xr)
bins <- function(v, edges) {
h <- hist(v, breaks = edges, plot = FALSE)
data.frame(lo = head(h$breaks, -1), hi = tail(h$breaks, -1), share = h$counts / max(h$counts))
}
hx <- bins(x, seq(xr[1], xr[2], length.out = 31))
hy <- bins(y, seq(yr[1], yr[2], length.out = 31))
xbreaks <- pretty(xr)
xbreaks <- xbreaks[xbreaks >= xr[1] & xbreaks <= xr[2]]
ybreaks <- pretty(yr)
ybreaks <- ybreaks[ybreaks >= yr[1] & ybreaks <= yr[2]]
p_txt <- if (ct$p.value < .001) "p < .001" else sprintf("p = %.3f", ct$p.value)
p <- ggplot(d, aes(x, y)) +
annotate("segment", x = xbreaks, xend = xbreaks, y = yr[1], yend = yr[2], colour = "#E5E5EA",
linewidth = 0.4) + # vertical grid inside the scatter only
geom_point(size = 1.8, colour = "#007AFF", alpha = 0.45, stroke = 0) +
geom_ribbon(data = grid, aes(x, ymin = lwr, ymax = upr), inherit.aes = FALSE, fill = "#FF9500",
alpha = 0.25) +
geom_line(data = grid, aes(x, fit), colour = "#FF9500", linewidth = 1) +
geom_rect(data = hx, aes(xmin = lo, xmax = hi, ymin = top, ymax = top + share * top_h),
inherit.aes = FALSE, fill = "#007AFF", alpha = 0.35, colour = "white", linewidth = 0.3) +
geom_rect(data = hy, aes(ymin = lo, ymax = hi, xmin = right, xmax = right + share * right_w),
inherit.aes = FALSE, fill = "#007AFF", alpha = 0.35, colour = "white", linewidth = 0.3) +
scale_x_continuous(breaks = xbreaks, expand = c(0.01, 0)) +
scale_y_continuous(breaks = ybreaks, expand = c(0.01, 0)) +
labs(title = "Pairs that trade more have more synchronised business cycles",
subtitle = sprintf("Pearson r = %.2f, 95%% CI [%.2f, %.2f], t(%d) = %.1f, %s · slope = %.2f · n = %d pairs (simulated)",
ct$estimate, ct$conf.int[1], ct$conf.int[2], ct$parameter, ct$statistic,
p_txt, coef(fit)[2], n),
x = "Bilateral trade intensity (log of trade / combined GDP)",
y = "Business-cycle correlation") +
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"),
axis.title.x = element_text(hjust = 0.4),
axis.title.y = element_text(hjust = 0.4),
panel.grid = element_blank())
print(p)
Figures use the optional PyStatlas style: add plt.style.use("pystatlas.mplstyle") to match the look exactly.
Data source
- 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. - Janicki, Warin & Wunnava (2009), endogenous optimum currency areas. Janicki, H., Warin, T., & Wunnava, P. (2009). Testing Mundell's intuition of endogenous OCA theory. Review of International Economics, 17(1), 74–86. https://doi.org/10.1111/j.1467-9396.2008.00802.x
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.
The examples illustrate statistical methods. Their numbers are simulated unless an entry says otherwise, and their titles describe what each figure shows in these simulated data — not findings of the cited papers, nor the author's position on the substantive question. For results, context and data, rely on the papers cited here.
How to cite
PyStatlas is created and maintained by Thierry Warin. If it helped your work, please cite it.
Warin, T. (2026). Scatterplot with statistics. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/correlation/scatter-with-stats/
@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}
}More in Correlation & association
Correlation matrix
Lower-triangle Pearson correlation heatmap; non-significant cells (Holm) are crossed out.
ggstatsplot::ggcorrmat()Pairs plot with correlations
Scatter matrix of four regional growth variables, with group KDEs on the diagonal and pooled vs within-group correlations above it.
GGally::ggpairs()Correlogram with clustering
Corrplot-style circles sized and coloured by r for 12 development indicators, ordered by hierarchical clustering.
corrplot::corrplot(order = "hclust", addrect = 3)