如何解决使用 python 将 statsmodel 表转换为乳胶样式 .png
我认为我非常接近于解决很多 statsmodel 用户过去遇到的问题。然而,我不存在的乳胶经验大大减缓了我的进步。 :D
让我们直接进入问题: 在下面,我使用来自 https://www.statsmodels.org/stable/regression.html 的示例数据集。
因此输出是以下回归表: OLS Regression Results
我尝试了几个包将输出转换为乳胶样式 .png。最有前途的方法似乎是使用 sympy.printing.preview.preview 函数:
在:
from sympy.printing.preview import preview
preamble = "\\documentclass[12pt]{article}\n" \
"\\usepackage{booktabs,amsmath,amsfonts}\\begin{document}"
preview(res.summary().as_latex(),output='png',filename='output.png',preamble=preamble)
如您所见,回归的第二个和第三个表以及表下方的警告与第一个表不符。
为了解决这个问题,我尝试使用 tabularx 包,如下所示:
preamble = "\\documentclass[12pt]{article}\n" \
"\\usepackage{booktabs,amsfonts,tabularx}\\begin{document}"
preview(res.summary().as_latex().replace("\\begin{tabular}","\\begin{tabularx}
{\\textwidth}").replace("\\end{tabular}","\\end{tabularx}"),preamble=preamble)
表二和表三的水平线与表一的水平线对齐,但表的输入和警告不是。
有人知道如何从这里继续吗?如何使用 python 获取以 .png 格式保存的乳胶样式的原始输出表?
提前谢谢你们!
编辑 1:
由于 res.summary().as_latex()
输出了帖子末尾显示的代码,我已经设法或多或少地手动对齐表格:
preview(res.summary().as_latex().replace("\\begin{tabular}","\\begin{tabularx}{20cm}").replace("\\end{tabular}","\\end{tabularx}").replace("{lclc}","{>{\hsize=.3\hsize}X >{\hsize=.2\hsize}X >{\hsize=.3\hsize}X >{\hsize=.2\hsize}X}").replace("{lcccccc}","{XXXXXX p{3.6cm}}"),preamble=preamble)
new Output looks like that。这不应该也不能成为最终解决方案,因此如果有人知道一种更动态(非手动)的方法来做到这一点,我想扩大这个问题。
三个表的完整乳胶代码:
\begin{center}
\begin{tabular}{lclc}
\toprule
\textbf{Dep. Variable:} & y & \textbf{ R-squared: } & 0.416 \\
\textbf{Model:} & OLS & \textbf{ Adj. R-squared: } & 0.353 \\
\textbf{Method:} & Least Squares & \textbf{ F-statistic: } & 6.646 \\
\textbf{Date:} & Thu,04 Feb 2021 & \textbf{ Prob (F-statistic):} & 0.00157 \\
\textbf{Time:} & 18:38:15 & \textbf{ Log-Likelihood: } & -12.978 \\
\textbf{No. Observations:} & 32 & \textbf{ AIC: } & 33.96 \\
\textbf{Df Residuals:} & 28 & \textbf{ BIC: } & 39.82 \\
\textbf{Df Model:} & 3 & \textbf{ } & \\
\bottomrule
\end{tabular}
\begin{tabular}{lcccccc}
& \textbf{coef} & \textbf{std err} & \textbf{t} & \textbf{P$> |$t$|$} & \textbf{[0.025} & \textbf{0.975]} \\
\midrule
\textbf{x1} & 0.4639 & 0.162 & 2.864 & 0.008 & 0.132 & 0.796 \\
\textbf{x2} & 0.0105 & 0.019 & 0.539 & 0.594 & -0.029 & 0.050 \\
\textbf{x3} & 0.3786 & 0.139 & 2.720 & 0.011 & 0.093 & 0.664 \\
\textbf{const} & -1.4980 & 0.524 & -2.859 & 0.008 & -2.571 & -0.425 \\
\bottomrule
\end{tabular}
\begin{tabular}{lclc}
\textbf{Omnibus:} & 0.176 & \textbf{ Durbin-Watson: } & 2.346 \\
\textbf{Prob(Omnibus):} & 0.916 & \textbf{ Jarque-Bera (JB): } & 0.167 \\
\textbf{Skew:} & 0.141 & \textbf{ Prob(JB): } & 0.920 \\
\textbf{Kurtosis:} & 2.786 & \textbf{ Cond. No. } & 176. \\
\bottomrule
\end{tabular}
%\caption{OLS Regression Results}
\end{center}
Notes: \newline
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。