在ggplot中添加多个线性回归方程可以通过使用geom_smooth()函数和stat_poly_eq()函数来实现。下面是完善且全面的答案:
要将多个线性回归方程添加到ggplot的底部,可以按照以下步骤进行操作:
library(ggplot2)
p <- ggplot(data = df, aes(x = x, y = y)) + geom_point()
p <- p + geom_smooth(method = "lm", se = FALSE)
stat_poly_eq <- function(formula, coef.digits = 2, rr.digits = 2, ...) {
lm_eq <- function(formula) {
fit <- lm(formula)
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(fit$coef[[1]], digits = coef.digits),
b = format(fit$coef[[2]], digits = coef.digits),
r2 = format(summary(fit)$r.squared, digits = rr.digits)))
as.character(as.expression(eq))
}
geom <- ggplot2:::ggplot2::GeomFunction$new(
fun = function(x, y, ...) {
label <- paste(lm_eq(y ~ x), sep = ", ")
data.frame(x = mean(x), y = min(y), label = label)
}, ...)
ggplot2:::ggplot_add(geom)
}
p <- p + stat_poly_eq(formula = y ~ x)
library(ggplot2)
# 创建一个示例数据框
df <- data.frame(x = c(1, 2, 3, 4, 5), y = c(2, 4, 6, 8, 10))
# 创建基本的ggplot对象并添加散点图和线性回归线
p <- ggplot(data = df, aes(x = x, y = y)) + geom_point() +
geom_smooth(method = "lm", se = FALSE)
# 创建自定义函数用于添加回归方程
stat_poly_eq <- function(formula, coef.digits = 2, rr.digits = 2, ...) {
lm_eq <- function(formula) {
fit <- lm(formula)
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(fit$coef[[1]], digits = coef.digits),
b = format(fit$coef[[2]], digits = coef.digits),
r2 = format(summary(fit)$r.squared, digits = rr.digits)))
as.character(as.expression(eq))
}
geom <- ggplot2:::ggplot2::GeomFunction$new(
fun = function(x, y, ...) {
label <- paste(lm_eq(y ~ x), sep = ", ")
data.frame(x = mean(x), y = min(y), label = label)
}, ...)
ggplot2:::ggplot_add(geom)
}
# 使用自定义函数添加回归方程
p <- p + stat_poly_eq(formula = y ~ x)
# 添加图形标题和轴标签,并自定义图形样式
p <- p + labs(title = "Scatter plot with linear regression",
x = "X", y = "Y") +
theme(plot.title = element_text(hjust = 0.5),
axis.title = element_text(size = 12))
# 显示图形
print(p)
这样,你就可以将多个线性回归方程添加到ggplot的底部了。请注意,这只是一个示例,你可以根据自己的数据和需求进行相应的修改和定制。
领取专属 10元无门槛券
手把手带您无忧上云