5
votes

I'm trying to show data of two groups. I am using the ggplot2 package to graph the data and using stat_summary() to obtain a point estimate (mean) and 90% CI within the plot of the data. What I'd like is for the mean and confidence interval be structured off to the right of the points representing the distribution of the data. Currently, stat_summary() will simply impose the mean and CI over top of the distribution.

Here is an example of data that I am working with:

set.seed(9909)
Subjects <- 1:100
values <- c(rnorm(n = 50, mean = 30, sd = 5), rnorm(n = 50, mean = 35, sd = 8))
data <- cbind(Subjects, values)
group1 <- rep("group1", 50)
group2 <- rep("group2", 50)
group <- c(group1, group2)
data <- data.frame(data, group)
data

And this is what my current ggplot2 code looks like (distribution as points with the mean and 90% CI overlaid on top for each group):

ggplot(data, aes(x = group, y = values, group = 1)) +  
geom_point() + 
stat_summary(fun.y = "mean", color = "red", size = 5, geom = "point") +
stat_summary(fun.data = "mean_cl_normal", color = "red", size = 2, geom = "errorbar", width = 0, fun.args = list(conf.int = 0.9)) + theme_bw()

Is it possible to get the mean and confidence intervals to position_dodge to the right of their respective groups?

1
I don't know of some automatic way to do it, but you could add things manually by shifting where you plot on the x axis. For example, add mapping = aes(x = as.numeric(group)+.1) to one of your stat_summary calls. - aosmith
That worked really well. Thanks! - user3585829

1 Answers

7
votes

You can use position_nudge:

ggplot(data, aes(x = group, y = values, group = 1)) +  
  geom_point() + 
  stat_summary(fun.y = "mean", color = "red", size = 5, geom = "point",
               position=position_nudge(x = 0.1, y = 0)) +
  stat_summary(fun.data = "mean_cl_normal", color = "red", size = 2, 
               geom = "errorbar", width = 0, fun.args = list(conf.int = 0.9),
               position=position_nudge(x = 0.1, y = 0)) + 
  theme_bw()

enter image description here