【问题标题】:making bargraph ggplot in ggplot loop在ggplot循环中制作条形图ggplot
【发布时间】:2020-03-05 05:39:48
【问题描述】:

这个问题是对之前帖子的延伸: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"]])
```

【问题讨论】:

  • 嘿.. 只是为了澄清一下,你想阴谋什么?是每行一个图,还是每个条件一个图(x1,x2)

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


【解决方案1】:

每次观察都有一个 se 是没有意义的,如果您试图为每列绘制一个均值和 se 条形图,请执行以下操作:

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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-23
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多