2

this question is an extension of a previous posting: ggplot and loops

I was using the example above to generate bar graphs in a loop. I modified the above example, to generate a bar graph and corresponding error bars. I somewhat succeeded, however the error bars do not populate according to the individual variable.

I would appreciate the help very much!

My modifications:

#make a dummy dataframe
D <- data.frame(
  x1 = runif(20),
  x2 = rnorm(20),
  x1_se = runif(20, 0.01, 0.09),
  x2_se = runif(20, -1, 1),
  treatment = rep(c("control","test"), each = 10)
)

# for reference later
p_names <- c("treatment","x1","x2")
se_names <- c("treatment","x1_se","x2_se")
trt <- rep(c("control","test"), each = 10)

# subset the standard error into its own dataframe
se <- D[,se_names]
names(se) <- str_remove(names(se), "_se")

plots <- list()

# the loop
for(nm in p_names) {

  #trt <- trt
  plots[[nm]] <- ggplot(data= D,  aes(x = trt, fill = trt))  + 
    geom_bar(aes_string(y = D[[nm]]), stat="identity", position = "dodge", color = "black") +
    geom_errorbar(aes(ymin= D[[nm]] - se[[nm]], 
                      ymax=   D[[nm]] + se[[nm]]), position=position_dodge(.9)) + ylab(nm)
}

print(plots[["x1"]])
print(plots[["x2"]])
```
1
  • hey.. just to clarify, what are you trying to plot? Is it one plot for every row, or one plot for every condition (x1,x2) Commented Mar 5, 2020 at 7:29

1 Answer 1

1

It doesn't make sense to have one s.e per observation, if you are trying to plot a mean and se barplot for each column, do the below:

p_names = c("x1","x2")
for(nm in p_names) {
  plots[[nm]] <- ggplot(data= D,aes_string(x ="treatment",y=nm,fill="treatment"))+
    stat_summary(fun.y=mean,color = "black",geom="bar") +
    stat_summary(fun.data=mean_se,geom="errorbar",width=0.2)
}

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.