如何获取多组线性回归的斜率并在ggplot分面图中标注?
获取分组线性回归斜率并标注到ggplot图形中
一、提取各组回归斜率
按quantity(分面变量)和quality(分组变量)分别拟合线性模型,提取斜率值。可以用dplyr结合broom包高效完成:
library(dplyr) library(broom) library(ggplot2) # 分组拟合模型并提取斜率 slope_results <- donnees_tot %>% group_by(quantity, quality) %>% do(model_fit = lm(weight ~ temperature, data = .)) %>% mutate(slope = tidy(model_fit)$estimate[tidy(model_fit)$term == "temperature"]) %>% select(quantity, quality, slope) %>% ungroup() # 查看结果 print(slope_results)
二、将斜率(或完整回归方程)标注到图中
修改你的ggplot代码,加入geom_text(或geom_label),利用生成的斜率数据,将标注放在每个分面的合适位置:
1. 仅标注斜率值
g = ggplot(donnees_tot, aes(x=temperature, y=weight, col = quality))+ geom_point(size = 3)+ geom_smooth(method="lm", aes(col=quality, fill=quality))+ # lm方法下span参数无效,已移除 scale_color_manual(values=c("S" = "aquamarine3", "Y" = "darkgoldenrod3"))+ scale_fill_manual(values=c("S" = "aquamarine3", "Y" = "darkgoldenrod3"))+ scale_x_continuous(breaks=c(20,25,28), limits=c(20,28))+ # 添加斜率标注,调整x/y坐标到合适位置 geom_text(data = slope_results, aes(x = 27, y = max(donnees_tot$weight, na.rm = TRUE)*0.9, label = paste("斜率 =", round(slope, 2)), col = quality), hjust = 1)+ facet_wrap(~quantity) g
2. 标注完整回归方程(支持公式解析)
如果需要显示类似y = ax + b的公式,先生成公式文本,再用parse = TRUE解析:
# 生成包含截距和斜率的回归方程文本 equation_results <- donnees_tot %>% group_by(quantity, quality) %>% do(model_fit = lm(weight ~ temperature, data = .)) %>% mutate( intercept = tidy(model_fit)$estimate[tidy(model_fit)$term == "(Intercept)"], slope = tidy(model_fit)$estimate[tidy(model_fit)$term == "temperature"], # 生成ggplot可解析的公式文本 eqn = paste0("weight == ", round(intercept, 2), " + ", round(slope, 2), "*temperature") ) %>% select(quantity, quality, eqn) %>% ungroup() # 绘图并添加公式标注 g = ggplot(donnees_tot, aes(x=temperature, y=weight, col = quality))+ geom_point(size = 3)+ geom_smooth(method="lm", aes(col=quality, fill=quality))+ scale_color_manual(values=c("S" = "aquamarine3", "Y" = "darkgoldenrod3"))+ scale_fill_manual(values=c("S" = "aquamarine3", "Y" = "darkgoldenrod3"))+ scale_x_continuous(breaks=c(20,25,28), limits=c(20,28))+ geom_text(data = equation_results, aes(x = 27, y = max(donnees_tot$weight, na.rm = TRUE)*0.9, label = eqn, col = quality), hjust = 1, parse = TRUE)+ facet_wrap(~quantity) g
注意事项
span参数是给loess平滑方法用的,在method="lm"时不会生效,可直接移除。- 标注的
x和y坐标可根据数据范围调整,比如把y设为每组数据的最大值附近,避免遮挡数据点。
内容的提问来源于stack exchange,提问作者Nate Trf
相关产品推荐
相关产品推荐

