如何在R中将两个X变量对同一Y变量的回归线绘入同一图
在同一个图中绘制两条线性回归线(Number~Spending 和 Number~Score)
方法1:直接添加两条独立回归线
无需转换数据格式,通过两次调用geom_smooth()分别指定不同自变量,用颜色、线型区分两条线:
# 加载ggplot2包 library(ggplot2) # 构造你的数据集 Data <- data.frame( Spending = c(100, 200, 1000), Score = c(2, 26, 90), Number = c(5, 89, 65) ) # 绘制对比图 ggplot(Data, aes(y = Number)) + # 可选:添加原始散点,对应两个自变量的分布 geom_point(aes(x = Spending), color = "#2E86AB") + geom_point(aes(x = Score), color = "#F24C4C") + # 绘制Number ~ Spending的回归线 geom_smooth(aes(x = Spending), method = "lm", se = FALSE, color = "#2E86AB", linetype = "solid") + # 绘制Number ~ Score的回归线 geom_smooth(aes(x = Score), method = "lm", se = FALSE, color = "#F24C4C", linetype = "dashed") + # 设置标签与标题 labs(x = "自变量", y = "Number", title = "两条线性回归线斜率对比") + # 手动配置图例映射 scale_color_manual(values = c("#2E86AB", "#F24C4C"), labels = c("Number ~ Spending", "Number ~ Score")) + scale_linetype_manual(values = c("solid", "dashed"), labels = c("Number ~ Spending", "Number ~ Score")) + theme_minimal()
方法2:转换为长格式数据(更贴合ggplot设计逻辑)
先把宽格式数据转成长格式,将两个自变量合并为一列,通过分组一次性绘制两条回归线:
library(ggplot2) library(dplyr) library(tidyr) # 构造数据集 Data <- data.frame( Spending = c(100, 200, 1000), Score = c(2, 26, 90), Number = c(5, 89, 65) ) # 转换为长格式 Data_long <- Data %>% pivot_longer(cols = c(Spending, Score), names_to = "预测变量", values_to = "变量取值") # 绘制对比图 ggplot(Data_long, aes(x = 变量取值, y = Number, color = 预测变量, linetype = 预测变量)) + geom_point(size = 2) + geom_smooth(method = "lm", se = FALSE) + labs(title = "两条线性回归线斜率对比", x = "自变量取值", y = "Number") + scale_color_brewer(palette = "Set1") + theme_minimal()
核心细节说明
method = "lm"指定使用线性模型拟合回归线se = FALSE关闭置信区间(若需要展示,删除该参数即可)- 用颜色、线型区分两个模型,直观对比斜率差异
- 第二种长格式方法更简洁,也便于后续扩展更多模型
内容的提问来源于stack exchange,提问作者Olivia
相关产品推荐
相关产品推荐

