将 lm 摘要添加到绘图 RStudio
Adding lm summaries to plots RStudio
我正在使用 this tutorial 执行线性回归。有没有办法将线性模型的摘要(结果)添加到图中以便将其另存为 pdf。
这是代码:
scatter.smooth(x=cars$speed, y=cars$dist, main="Dist ~ Speed") # scatterplot
linearMod <- lm(dist ~ speed, data=cars) # build linear regression model on full data
print(linearMod)
#> Call:
#> lm(formula = dist ~ speed, data = cars)
#>
#> Coefficients:
#> (Intercept) speed
#> -17.579 3.932
summary(linearMod) # model summary
#> Call:
#> lm(formula = dist ~ speed, data = cars)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -29.069 -9.525 -2.272 9.215 43.201
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -17.5791 6.7584 -2.601 0.0123 *
#> speed 3.9324 0.4155 9.464 1.49e-12 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 15.38 on 48 degrees of freedom
#> Multiple R-squared: 0.6511, Adjusted R-squared: 0.6438
#> F-statistic: 89.57 on 1 and 48 DF, p-value: 1.49e-12
你想做的事情出奇的困难,这就是为什么大多数人不会选择那样做的原因:)
我能找到的最接近的解决方案使用 ggplot2
和许多其他包。可以执行以下操作:
- 使用
stargazer::stargazer()
创建回归模型的摘要 table
- 使用
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()
.
的输出添加 table 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)
```
这不是您想要的,因为它不使用 stargazer
,但它似乎比其他方法更直接(否则非常有指导意义和不错!),因此它可能会给您一些想法。当然,如果您使用任何包将 table 保存为 JPG 图片,您将能够使用与此相同的策略。
我将使用 cowplot
、ggplot2
和 modelsummary
包:
library('modelsummary')
library('ggplot2')
library('cowplot')
首先,我们估计一个模型并使用modelsummary
将table保存为PNG文件:
mod = lm(hp ~ mpg, mtcars)
modelsummary(mod, output = "table.png")
然后我们创建基本的 ggplot2
情节:
p = ggplot(mtcars, aes(hp, mpg)) +
geom_point() +
geom_smooth(method = "lm")
最后,我们使用 cowplot
包中的 ggdraw
和 draw_image
函数在我们的绘图中插入 table 图片:
ggdraw(p) +
draw_image("table.png", x = .6, y = .5, width = .3, height = .5)
我正在使用 this tutorial 执行线性回归。有没有办法将线性模型的摘要(结果)添加到图中以便将其另存为 pdf。
这是代码:
scatter.smooth(x=cars$speed, y=cars$dist, main="Dist ~ Speed") # scatterplot
linearMod <- lm(dist ~ speed, data=cars) # build linear regression model on full data
print(linearMod)
#> Call:
#> lm(formula = dist ~ speed, data = cars)
#>
#> Coefficients:
#> (Intercept) speed
#> -17.579 3.932
summary(linearMod) # model summary
#> Call:
#> lm(formula = dist ~ speed, data = cars)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -29.069 -9.525 -2.272 9.215 43.201
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -17.5791 6.7584 -2.601 0.0123 *
#> speed 3.9324 0.4155 9.464 1.49e-12 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 15.38 on 48 degrees of freedom
#> Multiple R-squared: 0.6511, Adjusted R-squared: 0.6438
#> F-statistic: 89.57 on 1 and 48 DF, p-value: 1.49e-12
你想做的事情出奇的困难,这就是为什么大多数人不会选择那样做的原因:)
我能找到的最接近的解决方案使用 ggplot2
和许多其他包。可以执行以下操作:
- 使用
stargazer::stargazer()
创建回归模型的摘要 table
- 使用
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()
.
我认为演示所有选项的最简单方法是在 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)
```
这不是您想要的,因为它不使用 stargazer
,但它似乎比其他方法更直接(否则非常有指导意义和不错!),因此它可能会给您一些想法。当然,如果您使用任何包将 table 保存为 JPG 图片,您将能够使用与此相同的策略。
我将使用 cowplot
、ggplot2
和 modelsummary
包:
library('modelsummary')
library('ggplot2')
library('cowplot')
首先,我们估计一个模型并使用modelsummary
将table保存为PNG文件:
mod = lm(hp ~ mpg, mtcars)
modelsummary(mod, output = "table.png")
然后我们创建基本的 ggplot2
情节:
p = ggplot(mtcars, aes(hp, mpg)) +
geom_point() +
geom_smooth(method = "lm")
最后,我们使用 cowplot
包中的 ggdraw
和 draw_image
函数在我们的绘图中插入 table 图片:
ggdraw(p) +
draw_image("table.png", x = .6, y = .5, width = .3, height = .5)