如何在图上添加拟合方程等标签
# 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
stat_smooth()
[ggplot2]stat_cor()
[ggpubr]stat_poly_eq()
[ggpmisc]
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/