【问题标题】:Fitting multiple different regression lines with ggplot用 ggplot 拟合多个不同的回归线
【发布时间】:2021-02-28 01:59:14
【问题描述】:

对于一个非常基本的演示,我试图证明对数转换线性模型是给定数据集的最佳模型。为了证明我希望将其与标准 lm、平方根等进行比较,以图形方式显示,与其他 2 相比,线性模型的对数变换最适合。问题是,如何创建多个重叠的不同 lm一个情节中的线条,?如果我可以给它们贴上标签那也很棒?

这是带有起始 ggplot 的示例真实数据

library(tidyverse)
p=runif(100,1,100)
q=6+3*log(p)+rnorm(100)
sample <- data.frame(p,q)
ggplot(data = sample) + 
geom_point(mapping = aes(x = p, y = q)) 

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您可以自己计算线条,例如像这样:

# Make a tibble containing name of transform and the actual function
transforms <- tibble(Transform = c("log", "sqrt", "linear"),
                     Function = list(log, sqrt, function(x) x))

# Compute the regression coefs and turn it into a tidy table
lm_df <- transforms %>% 
  group_by(Transform) %>%
  group_modify(~ {
    lm(q ~ .x$Function[[1]](p), data = sample) %>%
      broom::tidy() %>%
      select(term, estimate) %>%
      pivot_longer(estimate) %>%
      mutate(Function = .x$Function)
  }) 

> lm_df
# A tibble: 6 x 5
# Groups:   Transform [3]
  Transform term                name       value Function
  <chr>     <chr>               <chr>      <dbl> <list>  
1 linear    (Intercept)         estimate 12.6    <fn>    
2 linear    .x$Function[[1]](p) estimate  0.0834 <fn>    
3 log       (Intercept)         estimate  5.89   <fn>    
4 log       .x$Function[[1]](p) estimate  2.99   <fn>    
5 sqrt      (Intercept)         estimate  9.35   <fn>    
6 sqrt      .x$Function[[1]](p) estimate  1.11   <fn>   

# Evaluate the functions at different x values
lm_df <- lm_df %>%
  pivot_wider(names_from = term, values_from = value) %>%
  rename("Intercept" = `(Intercept)`, "Slope" = `.x$Function[[1]](p)`) %>%
  group_modify(~ {
    tibble(
      y = .x$Intercept + .x$Slope * .x$Function[[1]](seq(0, max(sample$p))),
      x = seq(0, max(sample$p))
    )
  }) 

> lm_df
# A tibble: 300 x 3
# Groups:   Transform [3]
   Transform     y     x
   <chr>     <dbl> <int>
 1 linear     12.6     0
 2 linear     12.7     1
 3 linear     12.8     2
 4 linear     12.9     3
 5 linear     12.9     4
 6 linear     13.0     5
 7 linear     13.1     6
 8 linear     13.2     7
 9 linear     13.3     8
10 linear     13.4     9
# ... with 290 more rows

# Plot the functions
ggplot() + 
  geom_point(data = sample, mapping = aes(x = p, y = q)) +
  geom_line(data = lm_df, aes(x = x, y = y, color = Transform))

【讨论】:

    【解决方案2】:

    这不处理标签(您可以使用annotate() 手动添加标签),但是:

    gg0 <- ggplot(data = sample, aes(x=p, y=q)) +  geom_point()
    gg0 + geom_smooth(method="lm", formula=y~x) + 
          geom_smooth(method="lm", formula=y~log(x), colour="red") +
          geom_smooth(method="lm", formula=y~sqrt(x), colour="purple")
    

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      相关资源
      最近更新 更多