Alirsd
Alirsd

Reputation: 113

how to have separated confidence intervals in ggplot2

I have the following code in R.

df <- data.frame(Region = rep(1:3,3), education = rep(1:3,each =3),
                 mean = runif(9,0,1) , lo = runif(9, -1 , 0), 
                 up = runif(9, 1, 2))

ggplot(df, aes(Region, mean)) + geom_point(size=4) +
 geom_errorbar(aes(ymin = lo, ymax = up))

As you can see, the confidence intervals intersect each other. But, what I want is to have three different confidence interval beside each other separated by the variable education, and possibly with three different colors. The same way we separate bar graphs by another categorical variables

Thanks

Upvotes: 1

Views: 1287

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24272

A solution could be:

library(ggplot2)
set.seed(1)
df <- data.frame(Region = rep(1:3,3), education = rep(1:3,each =3),
                 mean = runif(9,0,1) , lo = runif(9, -1 , 0), 
                 up = runif(9, 1, 2))

df$RegEdu <- with(df, interaction(Region,  education), drop = TRUE )

ggplot(df, aes(x=RegEdu, y=mean, colour=factor(education), 
       pch=factor(Region))) + geom_point(size=4) +
       geom_errorbar(aes(ymin = lo, ymax = up))

enter image description here

EDIT. Using facet_grid you can group together error bars by education

ggplot(df, aes(x=Region, y=mean, colour=factor(education))) + 
       geom_point(size=4) +
       geom_errorbar(aes(ymin = lo, ymax = up))+
       facet_grid(.~education)

enter image description here

Upvotes: 1

Related Questions