如何在ggplot中添加全局loess平滑线并保留分组颜色?
问题:添加Loess平滑线后出现多条趋势线而非全局线
我想创建一张带Loess平滑线的散点图,捕捉整个时间段的趋势。研究对象是孕妇,所以希望根据妊娠阶段给每个点上色,同时查看趋势线是否随孕周变化。但添加geom_smooth(method = "loess")后,出现了多条Loess线,而不是一条全局趋势线。
原代码:
scr_delivery_plot<- ggplot(sbk2, aes(x = as.numeric(gestational_age), y = as.numeric(scr), color = as.factor(status))) + geom_point()+ scale_color_manual(values = cols) delscrplt2<- scr_delivery_plot + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) print(delscrplt2+ ggtitle("Scr: +/- 14 day delivery definition") + labs(colour = "Trimesters+Delivery")) + geom_smooth(method = "loess")
解决办法
问题根源是你把color = as.factor(status)放在了全局的aes()映射中,ggplot会默认按这个分组变量分别绘制平滑线。要得到单条全局Loess线,只需将颜色映射限定在散点图层即可:
方案一:限定颜色映射到散点图层(推荐)
# 全局aes仅保留x、y轴映射 scr_delivery_plot <- ggplot(sbk2, aes(x = as.numeric(gestational_age), y = as.numeric(scr))) + # 仅让散点按妊娠阶段上色 geom_point(aes(color = as.factor(status))) + scale_color_manual(values = cols) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + ggtitle("Scr: +/- 14 day delivery definition") + labs(colour = "Trimesters+Delivery") + # 基于全部数据生成单条Loess平滑线 geom_smooth(method = "loess") print(scr_delivery_plot)
方案二:强制平滑线按全局分组
如果你想保留全局的颜色映射,也可以在geom_smooth()中显式指定分组为1,强制绘制单条全局线:
scr_delivery_plot<- ggplot(sbk2, aes(x = as.numeric(gestational_age), y = as.numeric(scr), color = as.factor(status))) + geom_point()+ scale_color_manual(values = cols) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + ggtitle("Scr: +/- 14 day delivery definition") + labs(colour = "Trimesters+Delivery") + # 强制绘制单条全局线 geom_smooth(method = "loess", aes(group = 1)) print(scr_delivery_plot)
内容的提问来源于stack exchange,提问作者longshot_ologist
相关产品推荐
相关产品推荐

