R中的分组条形图带误差线

17

我想绘制一个带误差条的分组条形图。这是我目前能够得到的图表类型,对我所需的内容来说还不错:

enter image description here

以下是我的脚本:

#create dataframe
Gene<-c("Gene1","Gene2","Gene1","Gene2")
count1<-c(12,14,16,34)
count2<-c(4,7,9,23)
count3<-c(36,22,54,12)
count4<-c(12,24,35,23)
Species<-c("A","A","B","B")
df<-data.frame(Gene,count1,count2,count3,count4,Species)
df

mean1<-mean(as.numeric(df[1,][c(2,3,4,5)]))
mean2<-mean(as.numeric(df[2,][c(2,3,4,5)]))
mean3<-mean(as.numeric(df[3,][c(2,3,4,5)]))
mean4<-mean(as.numeric(df[4,][c(2,3,4,5)]))
Gene1SpeciesA.stdev<-sd(as.numeric(df[1,][c(2,3,4,5)]))
Gene2SpeciesA.stdev<-sd(as.numeric(df[2,][c(2,3,4,5)]))
Gene1SpeciesB.stdev<-sd(as.numeric(df[3,][c(2,3,4,5)]))
Gene2SpeciesB.stdev<-sd(as.numeric(df[4,][c(2,3,4,5)]))

ToPlot<-c(mean1,mean2,mean3,mean4)

#plot barplot
plot<-matrix(ToPlot,2,2,byrow=TRUE)   #with 2 being replaced by the number of genes!
tplot<-t(plot)
BarPlot <- barplot(tplot, beside=TRUE,ylab="count",
                names.arg=c("Gene1","Gene2"),col=c("blue","red"))

#add legend
legend("topright", 
       legend = c("SpeciesA","SpeciesB"), 
       fill = c("blue","red"))

#add error bars
ee<-matrix(c(Gene1SpeciesA.stdev,Gene2SpeciesA.stdev,Gene1SpeciesB.stdev,Gene2SpeciesB.stdev),2,2,byrow=TRUE)*1.96/sqrt(4)   
tee<-t(ee)
error.bar(BarPlot,tplot,tee)

问题是我需要对50个基因和4个物种进行操作,所以我的脚本会变得非常冗长,我想这并不是最优的...我试图在这里寻求帮助,但我无法找到更好的方法来实现我想要的功能。如果我不需要误差线,我可以修改这个脚本,但棘手的部分是如何混合ggplot美丽的条形图和误差线! ;)
如果您有任何优化我的脚本的想法,我将非常感激!
非常感谢!

1
小心,通过执行t(plot)你完全颠倒了基因 ;) - Colonel Beauvel
1个回答

21

从您对df的定义开始,您可以在几行代码中完成此操作:

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

输入图像描述


谢谢!我现在遇到了这个错误 :/> df1 <- transform(df, mean=rowMeans(df[cols]), sd=apply(df[cols],1, sd)) Error in [.data.frame(df, cols) : object 'cols' not found - tlorin
抱歉,我忘记了cols是什么(实际上错误信息就是这个;)现在已经编辑过了! - Colonel Beauvel
太好了!非常感谢!! :) - tlorin
1
别担心,只要记住当你有一个数据框时,ggplot非常适合! - Colonel Beauvel
在这种情况下,position_dodge(.9)是如何工作的?具体来说,为什么是0.9的值? - Praveen Kumar-M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接