【问题标题】:Adding lm summaries to plots RStudio将 lm 摘要添加到绘图 RStudio
【发布时间】:2021-01-28 22:27:56
【问题描述】:

我正在使用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

【问题讨论】:

  • 你想要什么样的总结?只是回归方程还是看起来更像整个模型摘要的东西? This 帖子谈到将模型摘要放入图表中,尽管使用 ggplot 而不是 scatter.smooth

标签: r plot linear-regression


【解决方案1】:

你想做的事情非常困难,这就是为什么大多数人不会选择这样做:)

我能找到的最接近的解决方案使用ggplot2 和许多其他包。可以执行以下操作:

  1. 使用stargazer::stargazer() 创建回归模型的汇总表
  2. 使用kableExtra::as_image()将其转换为PNG图像文件
  3. 使用 grid::rasterGrob() 将 PNG 转换为 grob
  4. 使用 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)
```

【讨论】:

    【解决方案2】:

    这不是您想要的,因为它不使用stargazer,但它似乎比其他方法更直接(否则非常有启发性和好!),因此它可能会给您一些想法。当然,如果您使用任何包将表格保存为 JPG 图像,您将能够使用与此相同的策略。

    我将使用cowplotggplot2modelsummary 包:

    library('modelsummary')
    library('ggplot2')
    library('cowplot')
    

    首先,我们估计一个模型并使用modelsummary将表格保存为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 包中的ggdrawdraw_image 函数将表格图片插入到我们的绘图中:

    ggdraw(p) +
      draw_image("table.png", x = .6, y = .5, width = .3, height = .5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 2020-11-17
      • 1970-01-01
      • 2018-03-12
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多