在ggplot中添加方程和R方以及P值可以使用annotate函数,具体步骤如下:

  1. 首先需要用lm函数拟合数据,并提取出模型的拟合结果,即方程和R方和P值。

  2. 在ggplot中使用annotate函数,将方程和R方以及P值添加到图形中。

  3. 在添加方程和R方以及P值时,使用\n换行符实现换行。

以下是具体的代码和示例:

# 加载ggplot2包
library(ggplot2)

# 生成示例数据
set.seed(123)
x <- 1:10
y <- 2 * x + 5 + rnorm(10)

# 拟合数据
fit <- lm(y ~ x)

# 提取拟合结果
eq <- paste0('y = ', round(fit$coefficients[2], 2), 'x + ', round(fit$coefficients[1], 2))
r2 <- paste0('R^2 = ', round(summary(fit)$r.squared, 2))
p <- paste0('p = ', round(summary(fit)$coefficients[2, 4], 2))

# 绘制散点图并添加拟合曲线
ggplot(data.frame(x, y), aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = 'lm', se = FALSE) +

  # 添加方程和R方和P值
  annotate('text', x = 2, y = max(y), label = eq, hjust = 0, size = 5) +
  annotate('text', x = 2, y = max(y) - 5, label = r2, hjust = 0, size = 5) +
  annotate('text', x = 2, y = max(y) - 10, label = p, hjust = 0, size = 5)

运行上述代码,即可得到带有方程、R方和P值的散点图,如下图所示:

image.png

可以看到,方程、R方和P值都位于图形下方,使用了\n换行符实现换行。

R语言ggplot拟合曲线添加方程、R方和P值并换行

原文地址: https://www.cveoy.top/t/topic/mHHK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录