Reputation: 89
I would like to plot confidence intervals with shadow bands by groups in R. The ideal case is that the color of all bands stays the same (grey). I made some typos in ggplot2 and it somehow generates the plot I was expecting. While after correcting the typos, I could never get the plot I want. Could anyone explain what is going on here.
set.seed(42)
dat <- data.frame(educ = rep(c("level 1","level 2","level 3"),each = 10),
age = 65:69,value = c(seq(1,5,by=1),seq(1,5,by=1)-1,
seq(5,9,by=1),seq(5,9,by=1)-1,
seq(10,14,by=1),seq(10,14,by=1)-1),
sd = abs(rnorm(30)/10),
educ_child = rep(rep(c("HS","HS and above"),each= 5),3))
geom_ribbon
and a warning message.ggplot(dat,
aes(x = age,y=value,color = educ,linetype=educ_child))+
geom_line()+
geom_ribbon(aes(ymin = value-1.96*sd,
ymax = value+1.96*sd,aaaaa=educ_child,linetype=NA),alpha = .2)+
theme_light()
The warning message is:
Warning message: Ignoring unknown aesthetics: aaaaa
ggplot(dat,
aes(x = age,y=value,color = educ,linetype=educ_child))+
geom_line()+
geom_ribbon(aes(ymin = value-1.96*sd,
ymax = value+1.96*sd,group=educ_child,linetype=NA),alpha = .2)+
theme_light()
the error message is:
Error in f()
:
! Aesthetics can not vary with a ribbon
Run rlang::last_error()
to see where the error occurred.
ggplot(dat,
aes(x = age,y=value,color = educ,linetype=educ_child))+
geom_line()+
geom_ribbon(aes(ymin = value-1.96*sd,
ymax = value+1.96*sd,linetype=NA),alpha = .2)+
theme_light()
Upvotes: 0
Views: 1204
Reputation: 173803
The group
aesthetic should be the interaction between educ
and educ_child
, since there are separate ribbons for each subset within both of these variables:
ggplot(dat,
aes(x = age, y = value, color = educ, linetype = educ_child)) +
geom_line() +
geom_ribbon(aes(ymin = value - 1.96 * sd,
ymax = value + 1.96 * sd,
group = interaction(educ, educ_child), linetype = NA),
alpha = 0.2)+
theme_light()
Upvotes: 1