例如,我有几个这样的情节:
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T)
是否有可能将这些中的2个绘制在同一个图中?
答案 0 :(得分:3)
如果您只想添加其他功能,请添加另一个图层:+ geom_smooth()
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
个信息:
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
内以显示在图例
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"))