R-ggpmisc|回归曲线添加回归方程,R2,方差表,香不香?

时间:2022-07-22
本文章向大家介绍R-ggpmisc|回归曲线添加回归方程,R2,方差表,香不香?,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

散点图绘制回归曲线很常用,那么添加上回归方程,P值,R2或者方差结果表等可以展示更量化的信息。

那加起来复杂吗?还真不一定!

一 载入 R包

使用内置数据集

library(ggplot2) #加载ggplot2包
library(dplyr) #加载dplyr包
library(ggpmisc) #加载ggpmisc包
#展示 使用Species为setosa的亚集
iris2 <- subset(iris,Species == "setosa")head(iris2)  Sepal.Length Sepal.Width Petal.Length Petal.Width Species1          5.1         3.5          1.4         0.2  setosa2          4.9         3.0          1.4         0.2  setosa3          4.7         3.2          1.3         0.2  setosa4          4.6         3.1          1.5         0.2  setosa5          5.0         3.6          1.4         0.2  setosa6          5.4         3.9          1.7         0.4  setosa

二 回归曲线的可能性

1, 绘制点图,添加回归线

#散点图
p <- ggplot(iris2, aes(Sepal.Length, Sepal.Width)) +
  geom_point(color = "grey50",size = 3, alpha = 0.6)
#回归线
#添加回归曲线
p + stat_smooth(color = "skyblue", fill = "skyblue", method = "lm")

2, 连接点到线

p + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm")+
  stat_fit_deviations(formula = y ~ x, color = "skyblue")

3,添加回归公式

stat_poly_eq参数添加公式,内含参数可调整位置等

p + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm") +
  stat_poly_eq(
    aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')),
    formula = y ~ x,  parse = TRUE,
      size = 5, #公式字体大小
      label.x = 0.1,  #位置 ,0-1之间的比例
      label.y = 0.95)

4, 添加方差结果表

p +  ylim(2,5) + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm") +
  stat_poly_eq(
    aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')),
    formula = y ~ x,  parse = TRUE,size = 3,label.x = 0.1, label.y = 0.99) +
  stat_fit_tb(tb.type = 'fit.anova',
    label.y.npc = "top", label.x.npc = "left",
  )

注:此处仅为展示 ,label.y.npc 为另一种调整位置的方式 ,用label.y可完全避免重叠

如担心方差表和公示与图重叠,可以通过ggplot2 的 ylimxlim适当调整,然后调整位置即可。

5,细节优化方差表

上述方差表中的行名,列名,以及NA,,,稍加调整后,看起来更“专业”

p +  ylim(2,5) + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm") +
  stat_poly_eq(
    aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')),
    formula = y ~ x,  parse = TRUE,size = 4,label.x = 0.1, label.y = 0.95) +
  stat_fit_tb(method = "lm",
              method.args = list(formula = y ~ x),
              tb.type = "fit.anova",
              tb.vars = c(Effect = "term",
                          "df",
                          "M.S." = "meansq",
                          "italic(F)" = "statistic",
                          "italic(P)" = "p.value"),
              label.y = 0.87, label.x = 0.1,
              size = 4,
              parse = TRUE
  )

以上,使用ylim 和 label.y后,公示和方差表不重叠,也不遮挡点图!

其他:既然是ggplot2的扩展包,ggplot2的一些参数亦可使用:

ggplot2|详解八大基本绘图要素

ggplot2|theme主题设置,详解绘图优化-“精雕细琢”

ggplot2 |legend参数设置,图形精雕细琢

ggplot2|ggpubr进行“paper”组图合并

参考资料:

https://github.com/cran/ggpmisc