ggpmisc
包具有stat_poly_eq
专门为此任务构建的功能(但不限于线性回归)。使用与data
@Sathish 发布的相同,我们可以分别添加方程和 R2,但给出label.y.npc
不同的值。label.x.npc
如果需要可以调节。
library(ggplot2)
library(ggpmisc)
#> For news about 'ggpmisc', please, see https://www.r4photobiology.info/
set.seed(21318)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3*df$x + rnorm(100, sd = 40)
formula1 <- y ~ x
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, formula = formula1) +
stat_poly_eq(aes(label = paste(..eq.label.., sep = "~~~")),
label.x.npc = "right", label.y.npc = 0.15,
eq.with.lhs = "italic(hat(y))~`=`~",
eq.x.rhs = "~italic(x)",
formula = formula1, parse = TRUE, size = 5) +
stat_poly_eq(aes(label = paste(..rr.label.., sep = "~~~")),
label.x.npc = "right", label.y.npc = "bottom",
formula = formula1, parse = TRUE, size = 5) +
theme_bw(base_size = 16)
# using `atop`
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, formula = formula1) +
stat_poly_eq(aes(label = paste0("atop(", ..eq.label.., ",", ..rr.label.., ")")),
formula = formula1,
parse = TRUE) +
theme_bw(base_size = 16)
### bonus: including result table
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, formula = formula1) +
stat_fit_tb(method = "lm",
method.args = list(formula = formula1),
tb.vars = c(Parameter = "term",
Estimate = "estimate",
"s.e." = "std.error",
"italic(t)" = "statistic",
"italic(P)" = "p.value"),
label.y = "bottom", label.x = "right",
parse = TRUE) +
stat_poly_eq(aes(label = paste0("atop(", ..eq.label.., ",", ..rr.label.., ")")),
formula = formula1,
parse = TRUE) +
theme_bw(base_size = 16)
由reprex 包创建(v0.3.0)