前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ggplot2拓展功能:添加拟合公式(Equations, R2, BIC, AIC etc.)

ggplot2拓展功能:添加拟合公式(Equations, R2, BIC, AIC etc.)

作者头像
拴小林
发布2020-11-04 15:37:45
4.4K0
发布2020-11-04 15:37:45
举报
文章被收录于专栏:数据驱动实践数据驱动实践

如何在图上添加拟合方程等标签

代码语言:javascript
复制
# Load packages and set theme
library(ggpubr)
library(ggpmisc)
theme_set(
  theme_bw() +
    theme(legend.position = "top")
)
# Scatter plot
p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = Species), size = 3, alpha = 0.6) +
  scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07")) +
  scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))+
  facet_wrap(~Species)

p
  1. Add regression line, correlation coefficient and equantions of the fitted line. Key functions:
    • stat_smooth() [ggplot2]
    • stat_cor() [ggpubr]
    • stat_poly_eq()[ggpmisc]
代码语言:javascript
复制


formula <- y ~ x
p + 
  stat_smooth( aes(color = Species, fill = Species), method = "lm") +
  stat_cor(aes(color = Species), label.y = 4.4)+
  stat_poly_eq(
    aes(color = Species, label = ..eq.label..),
    formula = formula, label.y = 4.2, parse = TRUE)


Fit polynomial equation: Create some data: set.seed(4321) x <- 1:100 y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4) my.data <- data.frame(x, y, group = c("A", "B"), y2 = y * c(0.5,2), block = c("a", "a", "b", "b")) Fit polynomial regression line and add labels: # Polynomial regression. Sow equation and adjusted R2 formula <- y ~ poly(x, 3, raw = TRUE) p <- ggplot(my.data, aes(x, y2, color = group)) + geom_point() + geom_smooth(aes(fill = group), method = "lm", formula = formula) + stat_poly_eq( aes(label = paste(..eq.label.., ..adj.rr.label.., sep = "~~~~")), formula = formula, parse = TRUE ) ggpar(p, palette = "jco")

Note that, you can also display the AIC and the BIC values using ..AIC.label.. and ..BIC.label.. in the above equation. Other arguments (label.x, label.y) are available in the function stat_poly_eq() to adjust label positions.For more examples, type this R code: browseVignettes(“ggpmisc”). 具体指引详见 http://www.sthda.com/english/articles/32-r-graphics-essentials/131-plot-two-continuous-variables-scatter-graph-and-alternatives/

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-11-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据驱动实践 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档