如何在ggplot堆积条形图中添加标准偏差条并重新组织数据顺序?

时间:2017-11-22 02:22:28

标签: r

我试图改进我的分组条形图,并试图为每个条形图添加标准偏差,但我似乎在苦苦挣扎。此外,我想要预先对比"小组离开,"后对比"团体权利,"控制"左和"反cd47"在每个相应的小组内。

这是我的情节:

Plot

这是我的代码:

library(plyr)
library(tidyverse)
library(readxl)

t2<- read_excel("t2quant.xlsx")
summary(t2)

head(t2, n=12)


ggplot(data=t2, aes(x = Time, y = T2Value)) +
  scale_fill_manual(values=c('red', 'black'))+
  theme(legend.position="top") +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  geom_bar(aes(fill = Group),
  width = 0.7, position = position_dodge(width=0.7), stat="summary", fun.y = "mean")+
  scale_y_continuous(expand=c(0,0), limits = c(0,20))

这是我的数据,来自dput:

structure(list(Time = c("Pre_Contrast", "Pre_Contrast", "Pre_Contrast", 
"Pre_Contrast", "Pre_Contrast", "Pre_Contrast", "Post_Contrast", 
"Post_Contrast", "Post_Contrast", "Post_Contrast", "Post_Contrast", 
"Post_Contrast"), Group = c("Control", "Control", "Control", 
"Anti_CD47", "Anti_CD47", "Anti_CD47", "Control", "Control", 
"Control", "Anti_CD47", "Anti_CD47", "Anti_CD47"), T2Value = c(14, 
10.4, 11, 16.7, 15, 12, 6, 5.8, 6.5, 3.5, 3.7, 2.6)), .Names = c("Time", 
"Group", "T2Value"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-12L))

我是否可以通过mutate或其他方式将标准偏差添加到数据集中?或者我是否必须以完全水平的方式重新排列我的Excel工作表中的数据,如下所示?

预对比|控制|数据1 |数据2 |数据3 |意思是SD |

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

library(dplyr)
library(tidyr)

t2new <- t2 %>% 
    group_by(Time, Group) %>% 
    summarise(mean= mean(T2Value), sd = sd(T2Value))

ggplot(t2new, aes(Time, mean, fill=Group)) + 
  geom_bar(stat="identity", width = 0.7, position = position_dodge(width=0.7)) +
  geom_errorbar(aes(ymin=mean-1.96*sd, max=mean+1.96*sd), width=.2, position=position_dodge(width=0.7))

enter image description here