0

I'm hoping to incorporate multiple subsets into one geom_smooth function rather then having multiple geom_smooths in one graph - which will make it difficult when I want to incorporate a legend and different colouring options in RColorBrewer later. And it just looks messy right now.

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 The different curves are taken from the years in my dataset from 1966-1996 (right now as a factor variable in my data frame). I only want to plot the 4 years (1966,1976,1986,1996) right now.

I have a countries variable which has 200 countries, so at the moment I'm just looking at Spain.

I have tried the following code, but they don't work

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
Nautica
  • 2,004
  • 1
  • 12
  • 35
  • 1
    Have you tried adding `aes(group = year)` to `geom_smooth`? – mt1022 Aug 19 '17 at 14:10
  • That's done it, thanks. Added it to my first example. Does not work for my second example though, it still only produces the 1996 curve. – Nautica Aug 19 '17 at 14:20
  • In your second example, the subset specification in `geom_smooth` should be `year %in% c(1996, 1986, 1976, 1966)` rather than `year==c(1996, 1986, 1976, 1966)`, similar to the first example... – Z.Lin Aug 19 '17 at 14:30

0 Answers0