你想做的事情非常困难,这就是为什么大多数人不会选择这样做:)
我能找到的最接近的解决方案使用ggplot2 和许多其他包。可以执行以下操作:
- 使用
stargazer::stargazer() 创建回归模型的汇总表
- 使用
kableExtra::as_image()将其转换为PNG图像文件
- 使用
grid::rasterGrob() 将 PNG 转换为 grob
- 使用
ggplot2::annotation_custom() 将 table-as-image-as-grob 嵌入到 ggplot2 图表中
注意as_image() 需要some other packages and an installation of phantomjs。
这是一个例子:
但是,还有其他可能更好的解决方案,例如使用 ggpubr::stat_regline_equation() 的简单摘要或使用 broom::tidy() 的输出添加表 grob。
我认为演示所有选项的最简单方法是在 RMarkdown 文件中。这是复制到 RMarkdown 文件中的代码,您可以在 RStudio 中编写该文件。
---
title: "Regression"
author: "Neil Saunders"
date: "27/01/2021"
output:
html_document:
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE,
message = FALSE,
fig.path = "figures/")
library(ggplot2)
library(ggpubr)
library(broom)
library(gridExtra)
library(kableExtra)
library(grid)
library(sjPlot)
library(stargazer)
library(png)
theme_set(theme_bw())
```
# The model
```{r echo=TRUE}
linearMod <- cars %>%
lm(dist ~ speed, data = .)
```
# Visualizations
## Add equation and adjusted R-squared to a plot
```{r}
cars %>%
ggplot(aes(speed, dist)) +
geom_point() +
geom_smooth(method = "lm") +
stat_regline_equation(
aes(label = paste(..eq.label.., ..adj.rr.label.., sep = "~~~~"))
)
```
## Add tidy summary table to a plot
```{r}
linearMod_tidy <- tidy(linearMod)
cars %>%
ggplot(aes(speed, dist)) +
geom_point() +
geom_smooth(method = "lm") +
annotation_custom(tableGrob(linearMod_tidy,
theme = ttheme_default(base_size = 10)),
xmin = 0, ymin = 90)
```
## Add tabular summary and plot side-by-side
### stargazer
:::::: {.columns}
::: {.column width="48%" data-latex="{0.48\textwidth}"}
```{r}
cars %>%
ggplot(aes(speed, dist)) +
geom_point() +
geom_smooth(method = "lm")
```
:::
::: {.column width="4%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="48%" data-latex="{0.48\textwidth}"}
```{r results='asis'}
stargazer(linearMod, type = "html")
```
:::
::::::
### tab\_model
:::::: {.columns}
::: {.column width="48%" data-latex="{0.48\textwidth}"}
```{r echo=FALSE,}
cars %>%
ggplot(aes(speed, dist)) +
geom_point() +
geom_smooth(method = "lm")
```
:::
::: {.column width="4%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="48%" data-latex="{0.48\textwidth}"}
```{r}
tab_model(linearMod)
```
:::
::::::
## Add stargazer table to a plot
```{r}
imgfile <- stargazer(linearMod, type = "html") %>%
as_image()
img <- readPNG(imgfile)
g <- rasterGrob(img, interpolate = TRUE, width = 0.5, height = 0.5)
cars %>%
ggplot(aes(speed, dist)) +
geom_point() +
geom_smooth(method = "lm") +
annotation_custom(g, xmin = 1, xmax = 15, ymin = 50, ymax = 130)
```