在ggplot循环中制作条形图ggplot

时间:2020-03-05 05:39:48

标签: r ggplot2 plot data-visualization bar-chart

此问题是先前发布的扩展: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"]])
```

1 个答案:

答案 0 :(得分:1)

每个观察值只有一个秒是没有意义的,如果您想绘制每列的均值和小节图,请执行以下操作:

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