此问题是先前发布的扩展:ggplot and loops
我正在使用上面的示例在一个循环中生成条形图。我修改了上面的示例,以生成条形图和相应的误差线。我取得了一些成功,但是错误条并没有根据各个变量进行填充。
非常感谢您的帮助!
我的修改
#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"]])
```