如何在R语言的同一张图中标注两个回归方程?
给分组回归图添加回归方程标注
方法一:使用ggpmisc包(推荐,操作简便)
先安装并加载ggpmisc包,它可以自动拟合回归并生成标准格式的方程标签:
# 首次使用时安装包 install.packages("ggpmisc") library(ggpmisc)
修改你原有的ggplot代码,添加stat_poly_eq层即可自动为每组生成y=mx+c形式的方程及R²值:
ggplot(data=Test, aes(x=Year, y=Value, color = Factor)) + geom_point(size=2, shape=22) + geom_smooth(method='lm', se=FALSE) # 可选去掉置信区间,简化图表 scale_y_continuous(breaks=c(1,50, 100, 150, 200, 250, 300, 365)) + scale_x_continuous(breaks = Test$Year) + # 添加回归方程和R²标签 stat_poly_eq( aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")), formula = y ~ x, parse = TRUE, size = 4, position = position_dodge(width = 0.5) # 避免两组标签重叠 ) + theme(axis.text.x = element_text(color = "grey20", size = 10, angle = 0, hjust = .5, vjust = .5, face = "bold"), axis.text.y = element_text(color = "grey20", size = 10, angle = 0, hjust = .5, vjust = .5, face = "bold"))
参数说明:
..eq.label..对应回归方程,..rr.label..对应R²值,用~~~~分隔可让两者同行显示,换成\n则会换行parse=TRUE让ggplot解析数学表达式,正确渲染方程格式position_dodge的宽度可根据你的数据调整,确保标签不重叠
方法二:手动计算参数后添加标签(无需额外包)
如果不想安装新包,可通过dplyr分组计算回归系数,再手动生成标签:
library(dplyr) # 按Factor分组计算回归方程参数 eq_labels <- Test %>% group_by(Factor) %>% summarise( model = list(lm(Value ~ Year)), slope = coef(model[[1]])[["Year"]], intercept = coef(model[[1]])[["(Intercept)"]], # 生成保留两位小数的y=mx+c格式标签 eq_label = paste0("y = ", round(slope, 2), "x + ", round(intercept, 2)) ) # 绘制图表并添加自定义标签 ggplot(data=Test, aes(x=Year, y=Value, color = Factor)) + geom_point(size=2, shape=22) + geom_smooth(method='lm') + scale_y_continuous(breaks=c(1,50, 100, 150, 200, 250, 300, 365)) + scale_x_continuous(breaks = Test$Year) + # 将标签放在每组数据的右上方 geom_text( data = eq_labels, aes(x = max(Test$Year), y = predict(model[[1]], newdata = data.frame(Year = max(Test$Year))), label = eq_label, color = Factor), hjust = 1.1, size = 4, fontface = "bold" ) + theme(axis.text.x = element_text(color = "grey20", size = 10, angle = 0, hjust = .5, vjust = .5, face = "bold"), axis.text.y = element_text(color = "grey20", size = 10, angle = 0, hjust = .5, vjust = .5, face = "bold"))
这种方法能完全自定义标签的位置和格式,适合需要精细化调整的场景。
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

