在ggplot2同图中区分线条类型:黑色虚线与彩色平滑线设置
ggplot2 分别设置不同分组的线条样式
只显示拟合线的情况
如果你只需要保留拟合线,不需要原始数据的连线,直接在geom_smooth的映射中加入线型分组,再手动指定每组的线型即可:
修改后的代码:
ggplot(ctwo, aes(x = Scale.Size, y = Pattern.Energy)) + geom_smooth(aes(color = Distance, linetype = Distance), se = FALSE) + scale_color_manual(values = c("control" = "black", "2cm" = "#a8ddb5")) + scale_linetype_manual(values = c("control" = "dashed", "2cm" = "solid")) + labs(x = "Scale Size", y = "Pattern Energy") + theme_classic()
关键说明:
- 在
geom_smooth的aes参数中添加linetype = Distance,让线型与Distance分组绑定。 - 用
scale_linetype_manual指定control组为虚线("dashed"),2cm组为实线("solid")。 - 不要额外添加
geom_line,否则会覆盖拟合线的样式,导致所有线条变成同一样式。
需要同时显示拟合线和原始数据连线的情况
如果你需要同时展示拟合线和原始数据的连线,可以通过subset筛选分组数据,分别为每组设置线条样式:
代码示例:
ggplot(ctwo, aes(x = Scale.Size, y = Pattern.Energy)) + # 处理control组:拟合线和原始数据连线均为虚线 geom_smooth(data = subset(ctwo, Distance == "control"), aes(color = Distance), se = FALSE, linetype = "dashed") + geom_line(data = subset(ctwo, Distance == "control"), aes(color = Distance), linetype = "dashed") + # 处理2cm组:拟合线和原始数据连线均为实线 geom_smooth(data = subset(ctwo, Distance == "2cm"), aes(color = Distance), se = FALSE, linetype = "solid") + geom_line(data = subset(ctwo, Distance == "2cm"), aes(color = Distance), linetype = "solid") + scale_color_manual(values = c("control" = "black", "2cm" = "#a8ddb5")) + labs(x = "Scale Size", y = "Pattern Energy") + theme_classic()
关键说明:
- 用
subset(ctwo, Distance == "分组名")单独筛选每组数据,分别添加geom_smooth和geom_line。 - 为每组的线条单独指定
linetype参数,实现精准控制。
内容的提问来源于stack exchange,提问作者Vmoreno29
相关产品推荐
相关产品推荐

