Kallas
Kallas

Reputation: 89

Plotting confidence interval by group with ggplot2 in r

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.

simulated data

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))

These codes generate what I want, but there is an improper argument name (aaaaa) in 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

The plot I do want (but the argument name is wrong)

After removing this argument, there is an error message and no plot is generated

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.

After correcting this argument name to a reasonable one, the figure went wrong

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()

enter image description here

Upvotes: 0

Views: 1204

Answers (1)

Allan Cameron
Allan Cameron

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()

enter image description here

Upvotes: 1

Related Questions