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

R 如何使用ggplot在同一绘图中绘制两条平滑样条曲线?,r,ggplot2,R,Ggplot2,例如,我有两个这样的图: ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T) 是否可以将这两种类型的图形绘制到同一个图形中?如果您只想添加另一个功能,请添加另一层:+geom_smooth() 如果要添加来自不同数据帧的数据,请在geom_smooth中添加df信息: 最后,自定义颜色和图例: color参数需要

例如,我有两个这样的图:

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

是否可以将这两种类型的图形绘制到同一个图形中?

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


如果要添加来自不同数据帧的数据,请在
geom_smooth
中添加
df
信息:


最后,自定义颜色和图例:
color
参数需要在
aes
内才能显示在图例中


查找
gridExtra::grid。排列
,但尝试制作面,它将使用单个Legend为您提供更多缩放绘图。我希望在同一坐标系中绘制函数,而不是在一页上绘制两个绘图。如果您只想添加另一个功能,请添加另一层:
+geom_smooth()
例如:
ggplot(mpg,aes(displant,hwy))+geom_point()+geom_smooth(method=“lm”,formula=y~样条线::bs(x,3),se=T)+geom_smooth(method=“lm”,formula=y~样条线::bs(x,4),se=T)
可以:将其添加到
geom_smooth
+geom_smooth(data=mpg,aes(x=displ,y=cyl),method=“lm”,formula=y~spline::bs(x,4),se=T)
如果需要图例,根据颜色,将
颜色
放在aes内
ggplot(mpg,aes(displ,hwy))+geom_point()+geom_smooth(aes(color=“B”),method=“lm”,formula=y~样条线::bs(x,3),se=T)+geom_smooth(data=mpg,aes(x=displ,y=cyl,color=“A”),method=“lm”,formula=y~样条线::bs(x,4),se=T)+比例颜色手册(“图例标题”,数值=c(“A=”红色”,“B=”蓝色”)
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)
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)
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"))