简体   繁体   中英

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

我想要的情节(但参数名称错误)

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

在此处输入图像描述

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM