【问题标题】:How do I add multiple linear regression equations to the bottom of a ggplot?如何将多个线性回归方程添加到 ggplot 的底部?
【发布时间】:2020-08-06 17:20:06
【问题描述】:

我想在图的底部显示三个线性回归和 R2 值,以显示每个 C3H8 浓度的 O2 和偏差之间的相关性。

  C3H8    O2  bias
1   85 20.90  0.01
2   50 20.90  0.10
3   25 20.94  0.32
4   85 10.00 -1.22
5   50 10.00 -1.05
6   25 10.00 -1.29
7   85  0.10 -3.13
8   50  0.10 -2.39
9   25  0.10 -2.55

这是我用于 ggplot 的代码:

library(ggrepel)

ggplot(Data.Frame.1, aes(O2, bias)) +
  theme_bw() +
  theme(legend.position = 'bottom', plot.title = element_text(hjust=0.5)) + 
  geom_point(aes(colour = factor(C3H8))) +
  geom_line(aes(colour = factor(C3H8))) +
  geom_text_repel(aes(label=paste(bias),
                      hjust= 0.4,
                      vjust=-.8, colour = factor(C3H8)),
                  size = 3) +
  ggtitle(expression(O[2]~Bias)) + 
  labs(
    x = expression('O'[2]),
    y = "% bias",
    colour = expression('C'[3]*'H'[8]~(ppm))
  )

如果在图中包含线性回归没有意义,我可以将它们列为单独的表格或数据框。甚至是类似的东西:

https://cran.r-project.org/web/packages/jtools/vignettes/summ.html

【问题讨论】:

    标签: r ggplot2 linear-regression


    【解决方案1】:

    您可以使用下一个代码实现与您想要的类似的东西。对于模型,您可以使用broom,对于最终绘图,您可以使用patchwork:

    library(ggrepel)
    library(broom)
    library(gridExtra)
    library(patchwork)
    library(ggplot2)
    #Data
    df <- structure(list(C3H8 = c(85L, 50L, 25L, 85L, 50L, 25L, 85L, 50L, 
    25L), O2 = c(20.9, 20.9, 20.94, 10, 10, 10, 0.1, 0.1, 0.1), bias = c(0.01, 
    0.1, 0.32, -1.22, -1.05, -1.29, -3.13, -2.39, -2.55)), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9"))
    

    代码:

    #First plot
    G1 <- ggplot(Data.Frame.1, aes(O2, bias)) +
      theme_bw() +
      theme(legend.position = 'bottom', plot.title = element_text(hjust=0.5)) + 
      geom_point(aes(colour = factor(C3H8))) +
      geom_line(aes(colour = factor(C3H8))) +
      geom_text_repel(aes(label=paste(bias),
                          hjust= 0.4,
                          vjust=-.8, colour = factor(C3H8)),
                      size = 3) +
      ggtitle(expression(O[2]~Bias)) + 
      labs(
        x = expression('O'[2]),
        y = "% bias",
        colour = expression('C'[3]*'H'[8]~(ppm))
      )
    #Models
    regs <- df %>% group_by(C3H8) %>%
      do(fit = lm(bias ~ O2 , data = .))
    coeffs <- tidy(regs,fit)
    #Format
    coeffs[,-c(1,2)] <- round(coeffs[,-c(1,2)],3)
    #Arrange new plot
    G2 <- G1 / tableGrob(coeffs)
    

    输出:

    我不确定lm() 中您想要的关系是否为bias ~ O2,但您可以更改它。

    【讨论】:

      猜你喜欢
      • 2021-01-14
      • 2018-05-28
      • 2014-11-03
      • 2021-03-25
      • 2021-10-25
      • 2013-03-16
      • 2021-04-16
      • 2015-05-08
      相关资源
      最近更新 更多