R使用ggplot2绘制带误差棒分组条形图复现示例时报错求助
你代码中定义的cols列索引超出了数据框实际列数,是触发报错的核心原因。你构建的df仅包含Gene、count1、count2、count3、count4、Species共6列,指定索引2-11属于读取不存在的列,自然会触发数据操作类报错。
修正后的完整可运行代码如下:
library(ggplot2) # 创建数据框 Gene<-c("IMR-90","Normal","IMR-90","Normal","IMR-90","Normal","IMR-90","Normal","IMR-90","Normal") count1<-c(100,100,92.2453,81.76718,83.326,80.61812,78.34494,85.92033,69.75771,79.64783) count2<-c(100,100,92.2453,81.76718,83.326,80.61812,78.34494,85.92033,69.75771,79.64783) count3<-c(100,100,92.2453,81.76718,83.326,80.61812,78.34494,85.92033,69.75771,79.64783) count4<-c(100,100,92.2453,81.76718,83.326,80.61812,78.34494,85.92033,69.75771,79.64783) Species<-c("0","0","1","1","2","2","3","3","4","4") # 修正列索引,仅选中4个count数值列 cols = c(2,3,4,5) df<-data.frame(Gene,count1,count2,count3,count4,Species) df1 = transform(df, mean=rowMeans(df[cols]), sd=apply(df[cols],1, sd)) # 绘图 ggplot(df1, aes(x=as.factor(Gene), y=mean, fill=Species)) + geom_bar(position=position_dodge(0.9), stat="identity", colour='black') + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2,position=position_dodge(0.9)) + labs(x = "分组", y = "均值", fill = "类别") + theme_bw()
运行上述代码即可得到预期的分组条形图效果,示例效果如下:
内容的提问来源于stack exchange,提问作者Yalzeee
相关产品推荐
相关产品推荐

