繁体   English   中英

如何将多个线性回归方程添加到 ggplot 的底部?

[英]How do I add multiple linear regression equations to the bottom of a ggplot?

我想在 plot 的底部显示三个线性回归和 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))
  )

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

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

您可以使用下一个代码类似于您想要的东西。 对于模型,您可以使用broom和最终的 plot 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)

output:

在此处输入图像描述

我不确定你在lm()中想要的关系是否是bias ~ O2但你可以改变它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM