R语言ggplot绘图添加拟合直线方程和R平方
可以使用ggplot2的annotate函数在图形上添加方程和R方。具体步骤如下:
- 用geom_smooth函数拟合直线,可以选择线性回归或其他回归模型。
- 提取拟合直线的斜率、截距和r方值。
- 使用annotate函数在图形上添加文本注释,包括方程和r方值。
以下是一个示例代码:
library(ggplot2)
# 创建数据
set.seed(123)
x <- rnorm(20)
y <- 2*x + rnorm(20)
# 绘制散点图和拟合直线
ggplot(data = data.frame(x, y), aes(x, y)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
# 提取拟合直线的斜率、截距和r方值
fit <- lm(y ~ x)
slope <- round(coef(fit)[2], 2)
intercept <- round(coef(fit)[1], 2)
r2 <- round(summary(fit)$r.squared, 2)
# 在图形上添加方程和r方值
ggplot(data = data.frame(x, y), aes(x, y)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
annotate("text", x = max(x), y = max(y), label = paste("y =", slope, "x +", intercept, sep = ""), hjust = 1) +
annotate("text", x = max(x), y = max(y) - 1, label = paste("R² =", r2), hjust = 1)
运行代码后,可以得到一张散点图和拟合直线,并在图形上添加了方程和r方值的注释。
原文地址: https://www.cveoy.top/t/topic/mHwD 著作权归作者所有。请勿转载和采集!