例如,我有几个这样的图:
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T)
Run Code Online (Sandbox Code Playgroud)
是否可以将 2 个此类绘制到同一个图中?
如果您只想添加另一个功能,请添加另一个层:+ 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)
Run Code Online (Sandbox Code Playgroud)
如果您想从不同的数据框中添加数据,请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)
Run Code Online (Sandbox Code Playgroud)
最后,自定义颜色和图例:
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"))
Run Code Online (Sandbox Code Playgroud)