user3426705
user3426705

Reputation: 23

making bargraph ggplot in ggplot loop

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"]])
```

Upvotes: 2

Views: 860

Answers (1)

StupidWolf
StupidWolf

Reputation: 46888

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

Upvotes: 1

Related Questions