如何在ggplot2 geom_smooth中使用(因子)变量的多个子集?

时间:2017-08-19 14:03:21

标签: r ggplot2

我希望将多个子集合并到一个geom_smooth函数中,而不是在一个图形中包含多个geom_smooths - 这将使我在以后想要在RColorBrewer中合并图例和不同的着色选项时变得困难。它现在看起来很乱。

Spain <- ggplot(dm, aes(valueage, meanvalue)) + 
geom_smooth(data=subset(dm, country == "Spain" & year==1996), aes(valueage, meanvalue), method = "lm", formula = y ~ splines::bs(x,knot=18), se=FALSE) +
geom_smooth(data=subset(dm, country == "Spain" & year==1986), aes(valueage, meanvalue), method = "lm", formula = y ~ splines::bs(x,knot=18), se=FALSE) +
geom_smooth(data=subset(dm, country == "Spain" & year==1976), aes(valueage, meanvalue), method = "lm", formula = y ~ splines::bs(x,knot=18), se=FALSE) +
geom_smooth(data=subset(dm, country == "Spain" & year==1966), aes(valueage, meanvalue), method = "lm", formula = y ~ splines::bs(x,knot=18), se=FALSE) +
scale_x_continuous(breaks = c(5:19), name="Age (years)") + 
scale_y_continuous(name="Mean height (cm)") +
theme(axis.line=element_line())
Spain

Output of above code 不同的曲线取自我1966 - 1996年的数据集中的年份(现在作为我的数据框中的因子变量)。我现在只想绘制4年(1966,1976,1986,1996)。

我有一个国家变量,有200个国家,所以目前我只是看着西班牙。

我尝试了以下代码,但他们没有工作

Spain <- ggplot(dm, aes(valueage, meanvalue)) +
geom_smooth(data=subset(dm, country == "Spain" & year %in% c(1996,1986,1976,1966)), aes(valueage, meanvalue), method = "lm", formula = y ~ splines::bs(x,knot=18), se=FALSE)
scale_x_continuous(breaks = c(5:19), name="Age (years)") + 
scale_y_continuous(name="Mean height (cm)") +
theme(axis.line=element_line())
Spain
##################
Spain <- ggplot(dm, aes(valueage, meanvalue)) +
geom_smooth(data=subset(dm, country == "Spain" & year==c(1996, 1986, 1976, 1966)), aes(valueage, meanvalue, group=year), method = "lm", formula = y ~ splines::bs(x,knot=18), se=FALSE)
scale_x_continuous(breaks = c(5:19), name="Age (years)") + 
scale_y_continuous(name="Mean height (cm)") +
theme(axis.line=element_line())
Spain

0 个答案:

没有答案