Grouped barplot in R with error bars

前端 未结 1 661
不知归路
不知归路 2020-11-29 10:50

I would like to draw a grouped barplot with error bars. Here is the kind of figure I have been able to get up to now, and this is ok for what I need:

相关标签:
1条回答
  • 2020-11-29 11:08

    Starting from your definition of df, you can do this in a few lines:

    library(ggplot2)
    
    cols = c(2,3,4,5)
    df1  = transform(df, mean=rowMeans(df[cols]), sd=apply(df[cols],1, sd))
    
    # df1 looks like this
    #   Gene count1 count2 count3 count4 Species  mean        sd
    #1 Gene1     12      4     36     12       A 16.00 13.856406
    #2 Gene2     14      7     22     24       A 16.75  7.804913
    #3 Gene1     16      9     54     35       B 28.50 20.240224
    #4 Gene2     34     23     12     23       B 23.00  8.981462
    
    ggplot(df1, aes(x=as.factor(Gene), y=mean, fill=Species)) +
      geom_bar(position=position_dodge(), stat="identity", colour='black') +
      geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2,position=position_dodge(.9))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题