如何在ggplot的geom_smooth中按回归线斜率设置颜色或线条粗细
实现方法
你需要先预先计算每个受试者对应的回归斜率,再将斜率映射为ggplot的颜色或线条大小美学即可,具体操作如下:
步骤1:计算每位受试者的回归斜率
先对数据集按ID分组,拟合每个ID的线性模型并提取斜率,再将斜率匹配回原始数据集:
library(dplyr) # 按ID分组计算回归斜率 slope_data <- mydata %>% group_by(ID) %>% summarise(lm_slope = coef(lm(continuous_outcome ~ age, data = cur_data()))[[2]]) # 合并斜率到原数据集 mydata_new <- left_join(mydata, slope_data, by = "ID")
步骤2:按斜率调整可视化效果
你可以按需选择以下任意一种或组合实现效果:
- 效果1:斜率越高颜色越偏红
ggplot(mydata_new, aes(x = age, y = continuous_outcome, group = ID)) + geom_smooth(aes(color = lm_slope), method = "lm", formula = y~x, se = FALSE, size = 0.5) + # 颜色渐变:低斜率为浅蓝色,高斜率为深红色 scale_color_gradient(low = "lightblue", high = "darkred") + theme(legend.position = "none") # 不需要图例就保留这句,需要看斜率对应值就删掉
- 效果2:斜率越高线条越粗
ggplot(mydata_new, aes(x = age, y = continuous_outcome, group = ID)) + geom_smooth(aes(size = lm_slope), method = "lm", formula = y~x, se = FALSE, color = "gray30") + # 调整线条粗细范围,可按需修改 scale_size_continuous(range = c(0.2, 2)) + theme(legend.position = "none")
- 效果3:同时调整颜色和粗细,识别度更高
ggplot(mydata_new, aes(x = age, y = continuous_outcome, group = ID)) + geom_smooth(aes(color = lm_slope, size = lm_slope), method = "lm", formula = y~x, se = FALSE) + scale_color_gradient(low = "lightblue", high = "darkred") + scale_size_continuous(range = c(0.2, 2)) + theme(legend.position = "none")
可选优化:区分正负斜率
如果你的数据中存在斜率为负(随年龄增长结局指标下降)的情况,可以使用发散色盘更清晰区分升降趋势:
ggplot(mydata_new, aes(x = age, y = continuous_outcome, group = ID)) + geom_smooth(aes(color = lm_slope, size = abs(lm_slope)), method = "lm", formula = y~x, se = FALSE) + # 负斜率为蓝色,0附近为白色,正斜率为红色 scale_color_gradient2(low = "darkblue", mid = "white", high = "darkred", midpoint = 0) + scale_size_continuous(range = c(0.2, 2)) + theme(legend.position = "none")
内容的提问来源于stack exchange,提问作者tcvdb1992
相关产品推荐
相关产品推荐

