You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:54:08