stargazer 风格的回归表
三个嵌套 OLS 模型并排,系数下方是标准误,表尾是拟合统计量,按期刊表格排版。

每篇实证论文都有的表格:每个模型一列,系数占一行,其下是括号中的标准误,用星号表示显著性,表尾列出观测数、R²、调整 R²、残差标准误和 F 统计量。这正是 R 的 stargazer() 输出的格式;这里用 Great Tables(great_tables.GT)构建,并按 Econometrica 等期刊的版式排版:衬线字体、小型大写的编号标题、只用横线(顶部、列标题下方、统计量上方、底部),不用竖线。
背景是 Stojkov, Veljanovski & Warin (2024, Post-Communist Economies) 关于新兴欧洲经济增长、制度与政策因素的研究。数据为说明用的模拟数据,并非论文的数据或结果:n = 220 个国家-年份(11 个经济体 × 20 年)。模型 (1) 只含制度变量,(2) 加入投资和贸易开放度,(3) 再加入通货膨胀和政府消费。解释变量已标准化,因此每个系数是解释变量变化一个标准差时增长率的变化(百分点)。模型用 smf.ols() 估计;表格由 params、bse、pvalues、rsquared、fvalue 等组装,table.show() 在浏览器中打开它。
代码及图中文字均为英文。
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from great_tables import GT, loc, style
# Simulated data, set in the context of Stojkov, Veljanovski & Warin (2024) [stojkov2024growth]
# Data: 11 emerging-European economies × 20 years, six institutional and policy factors
rng = np.random.default_rng(2024)
n = 220
labels = {"rule_law": "Rule of law", "reg_quality": "Regulatory quality",
"investment": "Investment (% of GDP)", "openness": "Trade openness",
"inflation": "Inflation", "gov_size": "Government consumption",
"Intercept": "Constant"}
predictors = list(labels)[:-1]
df = pd.DataFrame(rng.normal(size=(n, 6)), columns=predictors)
df["growth"] = (3 + 0.9 * df.rule_law + 0.45 * df.reg_quality + 0.8 * df.investment
+ 0.15 * df.openness - 0.7 * df.inflation - 0.05 * df.gov_size
+ rng.normal(0, 2.5, n))
df[predictors] = (df[predictors] - df[predictors].mean()) / df[predictors].std()
# Three nested models, each adding a block of predictors
blocks = [["rule_law", "reg_quality"], ["investment", "openness"], ["inflation", "gov_size"]]
models = [smf.ols("growth ~ " + " + ".join(sum(blocks[:k + 1], [])), data=df).fit()
for k in range(len(blocks))]
cols = [f"({k + 1})" for k in range(len(models))]
def stars(p):
return "***" if p < .01 else "**" if p < .05 else "*" if p < .1 else ""
def num(x, d=3): # typographic minus sign, as in print
return f"{x:.{d}f}".replace("-", "−")
# Body: a coefficient row and a standard-error row per term, as in stargazer
rows = []
for term, name in labels.items():
coef = {c: (num(m.params[term]) + stars(m.pvalues[term]) if term in m.params else "")
for c, m in zip(cols, models)}
se = {c: (f"({num(m.bse[term])})" if term in m.params else "") for c, m in zip(cols, models)}
rows += [{"term": name, **coef}, {"term": "", **se}]
n_body = len(rows)
coef_rows, se_rows = list(range(0, n_body, 2)), list(range(1, n_body, 2))
# Foot: fit statistics, one row each
rows += [
{"term": "Observations", **{c: f"{int(m.nobs)}" for c, m in zip(cols, models)}},
{"term": "R²", **{c: f"{m.rsquared:.3f}" for c, m in zip(cols, models)}},
{"term": "Adjusted R²", **{c: f"{m.rsquared_adj:.3f}" for c, m in zip(cols, models)}},
{"term": "Residual std. error", **{c: f"{np.sqrt(m.scale):.3f} (df = {m.df_resid:.0f})"
for c, m in zip(cols, models)}},
{"term": "F statistic", **{c: f"{m.fvalue:.2f}{stars(m.f_pvalue)} (df = {m.df_model:.0f}; {m.df_resid:.0f})"
for c, m in zip(cols, models)}},
]
tab = pd.DataFrame(rows)
table = (
GT(tab, rowname_col="term")
.tab_header(title="TABLE I",
subtitle="Institutions, policy and growth in emerging Europe")
.tab_spanner(label="Dependent variable: GDP-per-capita growth (%)", columns=cols, id="dep")
.cols_align("center", columns=cols)
.cols_width({"term": "190px", **{c: "185px" for c in cols}})
.tab_source_note("Notes: OLS estimates; standard errors in parentheses. Predictors are "
"standardised, so coefficients are percentage points of growth per 1 SD.")
.tab_source_note(f"n = {n} country-years (simulated). *p < 0.1; **p < 0.05; ***p < 0.01.")
# Econometrica look: serif type, small-caps title, horizontal rules only
.opt_table_font(font=["Latin Modern Roman", "Times New Roman", "Georgia", "serif"])
.tab_options(
table_width="745px", table_font_size="15px", table_font_color="#000",
heading_title_font_size="15px", heading_subtitle_font_size="15px", heading_padding="1px",
table_border_top_style="hidden", table_border_bottom_style="hidden",
heading_border_bottom_style="none",
column_labels_border_top_style="solid", column_labels_border_top_width="1.5px", # top rule
column_labels_border_top_color="#000",
column_labels_border_bottom_style="solid", column_labels_border_bottom_width="1px",
column_labels_border_bottom_color="#000",
table_body_hlines_style="hidden", stub_border_style="hidden",
table_body_border_bottom_style="solid", table_body_border_bottom_width="1.5px",
table_body_border_bottom_color="#000",
data_row_padding="4px", source_notes_font_size="13px", source_notes_padding="1px",
)
.tab_style(style.css("font-variant: small-caps; padding-bottom: 8px;"), loc.subtitle())
.tab_style(style.text(style="italic"), loc.spanner_labels(ids=["dep"]))
# standard error tucked under its coefficient
.tab_style(style.css("padding-bottom: 0;"), [loc.body(rows=coef_rows), loc.stub(rows=coef_rows)])
.tab_style(style.css("padding-top: 0;"), [loc.body(rows=se_rows), loc.stub(rows=se_rows)])
# thin rule between the coefficients and the fit statistics
.tab_style(style.borders(sides="top", style="solid", weight="1px", color="#000"),
[loc.body(rows=[n_body]), loc.stub(rows=[n_body])])
)
table.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. - Stojkov, Veljanovski & Warin (2024), European integration and growth in emerging Europe. Stojkov, A., Veljanovski, M., & Warin, T. (2024). European integration and economic growth in emerging Europe: The role of institutions and policy factors. Post-Communist Economies, 36(7), 778–800. https://doi.org/10.1080/14631377.2024.2376974
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). Regression table, stargazer style. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/academic-tables/regression-table/
@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}
}