1. ggplot拟合曲线换行:

如果需要在ggplot中添加拟合曲线的方程式并且需要换行,可以使用atop()函数来实现。具体方法是在方程式中需要换行的地方使用"\n"来换行,然后在方程式前面添加atop()函数即可。

例如,下面这个例子是在ggplot中添加了拟合曲线的方程式,并且需要在方程式中换行:

library(ggplot2)

# 创建数据
x <- 1:10
y <- c(3, 5, 7, 9, 11, 13, 15, 17, 19, 21)
df <- data.frame(x, y)

# 绘制散点图和拟合曲线
p <- ggplot(df, aes(x, y)) + geom_point() + geom_smooth(method = "lm", se = FALSE)

# 添加方程式并换行
p <- p + geom_text(aes(x = 2, y = 18, label = atop(paste("y =", round(coef(lm(y ~ x, data = df))[2], 2), "x +", round(coef(lm(y ~ x, data = df))[1], 2), "\nR^2 =", round(summary(lm(y ~ x, data = df))$r.squared, 2)), "")))
p
  1. ggplot添加拟合曲线的方程,r方和p值:

可以使用ggpmisc包中的stat_poly_eq()函数来添加拟合曲线的方程式、R方和p值。具体方法是在ggplot中使用stat_poly_eq()函数,并且设置label.y参数为0.15,这样就可以将方程式和R方、p值分别显示在图像的顶部和底部。

例如,下面这个例子是在ggplot中添加了拟合曲线的方程式、R方和p值:

library(ggplot2)
library(ggpmisc)

# 创建数据
x <- 1:10
y <- c(3, 5, 7, 9, 11, 13, 15, 17, 19, 21)
df <- data.frame(x, y)

# 绘制散点图和拟合曲线,并添加方程式、R方和p值
p <- ggplot(df, aes(x, y)) + 
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE) +
  stat_poly_eq(formula = y ~ x, 
               aes(label = paste(..eq.label.., sep = "~~~")), 
               parse = TRUE,
               label.x.npc = "right", label.y = 0.15) +
  stat_poly_eq(formula = y ~ x, 
               aes(label = paste("R^2 = ", signif(..r.squared.., 5), "   p = ", signif(..p.., 5), sep = "")), 
               parse = TRUE,
               label.x.npc = "right", label.y = 0.05)
p

注意:需要先安装并加载ggpmisc包才能使用stat_poly_eq()函数。

r语言ggplot拟合曲线上怎么换行r语言ggplot画图之后如何添加方程r方和p值简单方法

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

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