Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using position_dodge within stat_summary for means and confidence intervals?

Tags:

r

ggplot2

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?

like image 251
user3585829 Avatar asked Dec 23 '16 02:12

user3585829


1 Answers

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

like image 150
HubertL Avatar answered Sep 24 '22 06:09

HubertL