Comparing nested models
Coefficients of three nested FDI regressions side by side, to see how estimates shift as an EU block is added.

When covariates are added one block at a time, the interesting question is often not which terms are significant but how the estimates move. Here each term gets one row and each model one dodged dot-and-whisker, so you can follow a coefficient as the model grows. Hollow markers are not significant at 5%. The subtitle compares the models with R² and F-tests of the added blocks.
The setting is Stojkov & Warin (2018, Journal of East-West Business): EU
membership and foreign direct investment in transition economies. The data are
simulated for illustration — they are not the paper's data or results:
n = 180 country-years (10 economies × 18 years), with FDI inflows in % of GDP.
M1 holds market factors (market size, GDP growth, unit labour cost), M2 adds
policy (institutional quality, trade openness) and M3 adds the EU block
(candidate status, membership, both 0/1). Continuous predictors are
standardised. Institutions improve as countries approach the EU, so their
coefficient shrinks once the EU block enters. Models are fitted with smf.ols()
and compared with anova_lm().
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from statsmodels.stats.anova import anova_lm
# Simulated data, set in the context of Stojkov & Warin (2018) [stojkov2018fdi]
# Data: 10 transition economies × 18 years; EU candidate status precedes membership
rng = np.random.default_rng(2018)
year = np.tile(np.arange(18), 10)
entry = np.repeat(rng.integers(8, 14, 10), 18) # year of EU entry per country
df = pd.DataFrame({"candidate": ((year >= entry - 5) & (year < entry)).astype(int),
"member": (year >= entry).astype(int)})
df["size"], df["growth"], df["ulc"], df["openness"] = rng.normal(size=(4, 180))
df["institutions"] = 0.8 * df.candidate + 1.4 * df.member + rng.normal(0, 0.8, 180)
df["fdi"] = (4 + 0.8 * df["size"] + 0.6 * df.growth - 0.5 * df.ulc + 0.4 * df.openness
+ 0.3 * df.institutions + 1.0 * df.candidate + 1.8 * df.member
+ rng.normal(0, 1.8, 180))
X = ["size", "growth", "ulc", "institutions", "openness"]
df[X] = (df[X] - df[X].mean()) / df[X].std()
# Three nested models, each adding a block of predictors
formulas = {"M1 · market": "fdi ~ size + growth + ulc",
"M2 · + policy": "fdi ~ size + growth + ulc + institutions + openness",
"M3 · + EU block": "fdi ~ size + growth + ulc + institutions + openness + candidate + member"}
fits = {name: smf.ols(f, data=df).fit() for name, f in formulas.items()}
f_tests = anova_lm(*fits.values())
labels = {"size": "Market size", "growth": "GDP growth", "ulc": "Unit labour cost",
"institutions": "Institutional quality", "openness": "Trade openness",
"candidate": "EU candidate (0/1)", "member": "EU member (0/1)"}
terms = list(labels)[::-1]
palette = ["#007AFF", "#FF9500", "#34C759"]
fig, ax = plt.subplots(figsize=(8, 5.6))
ax.axvline(0, color="#8E8E93", lw=1, ls="--", zorder=1)
for k, ((name, m), c) in enumerate(zip(fits.items(), palette)):
offset = (1 - k) * 0.22 # dodge: first model on top
ci = m.conf_int()
for i, t in enumerate(terms):
if t not in m.params:
continue
sig = m.pvalues[t] < 0.05
ax.hlines(i + offset, ci.loc[t, 0], ci.loc[t, 1], color=c, lw=2.2, zorder=2)
ax.scatter(m.params[t], i + offset, s=55, zorder=3, lw=1.8,
color=c if sig else "white", edgecolor=c if not sig else "white")
ax.plot([], [], "o-", color=c, lw=2.2, ms=7,
label=f"{name} (R² = {m.rsquared:.2f})")
for i in range(len(terms) - 1): # thin separators between terms
ax.axhline(i + 0.5, color="#F2F2F7", lw=1, zorder=0)
ax.set_yticks(range(len(terms)), [labels[t] for t in terms])
ax.set_ylim(-0.6, len(terms) - 0.4)
ax.grid(axis="x"); ax.grid(axis="y", visible=False)
ax.set_xlabel("Change in FDI inflows, % of GDP per 1 SD or from 0 to 1 (95% CI)")
ax.legend(loc="center right", bbox_to_anchor=(1, 0.65), handlelength=1.6, borderaxespad=0.2)
ax.set_title("Institutions lose weight once EU status enters the model", pad=26)
fmt_p = lambda p: "p < .001" if p < .001 else f"p = {p:.3f}".replace("0.", ".")
blocks = [f"M{j} vs M{j + 1}: F({f_tests.df_diff[j]:.0f}, {f_tests.df_resid[j]:.0f}) = "
f"{f_tests.F[j]:.1f}, {fmt_p(f_tests['Pr(>F)'][j])}" for j in (1, 2)]
ax.text(0, 1.02, f"OLS · n = {int(fits['M1 · market'].nobs)} (simulated) · " + " · ".join(blocks)
+ " · hollow = p ≥ .05", transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
# Comparing nested models: the R equivalent of plot.py
# Simulated data, set in the context of Stojkov & Warin (2018) [stojkov2018fdi]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
library(broom)
set.seed(2018)
# Data: 10 transition economies × 18 years; EU candidate status precedes membership
year <- rep(0:17, 10)
entry <- rep(sample(8:13, 10, replace = TRUE), each = 18) # year of EU entry per country
df <- data.frame(candidate = as.integer(year >= entry - 5 & year < entry),
member = as.integer(year >= entry))
df$size <- rnorm(180); df$growth <- rnorm(180); df$ulc <- rnorm(180); df$openness <- rnorm(180)
df$institutions <- 0.8 * df$candidate + 1.4 * df$member + rnorm(180, 0, 0.8)
df$fdi <- with(df, 4 + 0.8 * size + 0.6 * growth - 0.5 * ulc + 0.4 * openness
+ 0.3 * institutions + 1.0 * candidate + 1.8 * member + rnorm(180, 0, 1.8))
X <- c("size", "growth", "ulc", "institutions", "openness")
df[X] <- scale(df[X])
# Three nested models, each adding a block of predictors
formulas <- c("M1 · market" = "fdi ~ size + growth + ulc",
"M2 · + policy" = "fdi ~ size + growth + ulc + institutions + openness",
"M3 · + EU block" = "fdi ~ size + growth + ulc + institutions + openness + candidate + member")
fits <- lapply(formulas, function(f) lm(as.formula(f), data = df))
f_tests <- do.call(anova, unname(fits)) # F-tests of each added block
labels <- c(size = "Market size", growth = "GDP growth", ulc = "Unit labour cost",
institutions = "Institutional quality", openness = "Trade openness",
candidate = "EU candidate (0/1)", member = "EU member (0/1)")
palette <- c("#007AFF", "#FF9500", "#34C759")
legend_lab <- sprintf("%s (R² = %.2f)", names(fits), sapply(fits, function(m) summary(m)$r.squared))
# One tidy table: estimate and 95% CI per term and model, dodged vertically (first model on top)
# (ggstats is not installed: broom::tidy() + ggplot2 do what ggcoef_compare() does)
coefs <- do.call(rbind, lapply(seq_along(fits), function(k) {
t <- subset(tidy(fits[[k]], conf.int = TRUE), term != "(Intercept)")
t$model <- factor(legend_lab[k], levels = legend_lab)
t$y <- (length(labels) + 1 - match(t$term, names(labels))) + (2 - k) * 0.22
t
}))
coefs$sig <- coefs$p.value < 0.05
fmt_p <- function(p) if (p < .001) "p < .001" else sub("0\\.", ".", sprintf("p = %.3f", p))
blocks <- sapply(2:3, function(j) sprintf("M%d vs M%d: F(%d, %d) = %.1f, %s", j - 1, j, f_tests$Df[j],
f_tests$Res.Df[j], f_tests$F[j], fmt_p(f_tests$`Pr(>F)`[j])))
p <- ggplot(coefs, aes(estimate, y, colour = model)) +
geom_hline(yintercept = seq(1.5, length(labels) - 0.5), colour = "#F2F2F7", linewidth = 0.5) +
geom_vline(xintercept = 0, colour = "#8E8E93", linewidth = 0.5, linetype = "dashed") +
geom_linerange(aes(xmin = conf.low, xmax = conf.high), linewidth = 1) +
# hollow = not significant at 5%
geom_point(aes(fill = ifelse(sig, as.character(model), "hollow")), shape = 21, size = 2.9,
stroke = 1.1) +
scale_colour_manual(NULL, values = setNames(palette, legend_lab)) +
scale_fill_manual(values = c(setNames(palette, legend_lab), hollow = "white"), guide = "none") +
scale_y_continuous(breaks = length(labels):1, labels = labels, expand = c(0, 0),
limits = c(0.4, length(labels) + 0.6)) +
labs(title = "Institutions lose weight once EU status enters the model",
subtitle = sprintf("OLS · n = %d (simulated) · %s · hollow = p ≥ .05", nobs(fits[[1]]),
paste(blocks, collapse = " · ")),
x = "Change in FDI inflows, % of GDP per 1 SD or from 0 to 1 (95% CI)", y = NULL) +
guides(colour = guide_legend(override.aes = list(fill = palette))) +
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.text.y = element_text(colour = "#1D1D1F", size = 10),
panel.grid.minor = element_blank(), panel.grid.major.y = element_blank(),
legend.position = "inside", legend.position.inside = c(0.99, 0.62),
legend.justification = c(1, 0.5),
legend.background = element_rect(fill = "white", colour = "#E5E5EA", linewidth = 0.3),
legend.text = element_text(size = 9.5))
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. - Stojkov & Warin (2018), EU membership and FDI. Stojkov, A., & Warin, T. (2018). EU membership and FDI: Is there an endogenous credibility effect? Journal of East-West Business, 24, 144–169. https://doi.org/10.1080/10669868.2018.1431579
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). Comparing nested models. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/regression-models/compare-models/
@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 Regression models
Coefficient plot
Regression estimates with 95% confidence intervals, one row per term.
ggstats::ggcoef_model()Odds-ratio forest plot
Logistic regression odds ratios on a log scale, with a table of OR [95% CI] alongside.
ggstats::ggcoef_model(exponentiate = TRUE)Predicted probabilities
Model-based probability curves with 95% CI ribbons across a predictor, by group.
ggeffects::ggpredict() / marginaleffects::plot_predictions()