如何使用ggplot在同一个绘图中绘制两个平滑样条曲线?

时间:2016-04-20 06:49:58

标签: r ggplot2

例如,我有几个这样的情节:

ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T)

是否有可能将这些中的2个绘制在同一个图中?

1 个答案:

答案 0 :(得分:3)

如果您只想添加其他功能,请添加另一个图层:+ geom_smooth()

Plot 1

ggplot(mpg, aes(displ, hwy)) + geom_point() + 
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T) +
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 4), se = T)

如果您想要添加其他数据框中的数据,请在df中添加geom_smooth个信息:

plot 2

ggplot(mpg, aes(displ, hwy)) + geom_point() + 
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T) + 
geom_smooth(data = mpg, aes(x = displ, y = cyl), method = "lm", formula = y ~ splines::bs(x, 4), se = T)

最后,自定义颜色和图例: color参数必须位于aes内以显示在图例

enter image description here

ggplot(mpg, aes(displ, hwy)) + geom_point() + 
geom_smooth(aes(color = "B"),method = "lm", formula = y ~ splines::bs(x, 3), se = T) + 
geom_smooth(data = mpg, aes(x = displ, y = cyl, color = "A"), method = "lm", formula = y ~ splines::bs(x, 4), se = T) + 
scale_color_manual("Legend Title", values = c("A" = "red", "B" = "blue"))