In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

我是 R 的新手,之前没有做过任何编程...

当我尝试创建带有标准误差条的箱线图时,我收到标题中提到的错误消息。

我使用了我在 R Cookbook 上找到的脚本,我对其进行了一些调整:

ggplot(GVW, aes(x="variable",y="value",fill="Genotype")) + 
  geom_bar(position=position_dodge(),stat="identity",colour="black", size=.3)+
  geom_errorbar(data=GVW[1:64,3],aes(ymin=value-seSKO, ymax=value+seSKO), size=.3, width=.2, position=position_dodge(.9))+
  geom_errorbar(data=GVW[65:131,3],aes(ymin=value-seSWT, ymax=value+seSWT), size=.3, width=.2, position=position_dodge(.9))+
  geom_errorbar(data=GVW[132:195,3],aes(ymin=value-seEKO, ymax=value+seEKO), size=.3, width=.2, position=position_dodge(.9))+
  geom_errorbar(data=GVW[196:262,3],aes(ymin=value-seEWT, ymax=value+seEWT), size=.3, width=.2, position=position_dodge(.9))+
  xlab("Time")+
  ylab("Weight [g]")+
  scale_fill_hue(name="Genotype", breaks=c("KO", "WT"), labels=c("Knock-out", "Wild type"))+
  ggtitle("Effect of genotype on weight-gain")+
  scale_y_continuous(breaks=0:20*4) +
  theme_bw()

Data<- data.frame(
  Genotype<- sample(c("KO","WT"), 262, replace=T),
  variable<- sample(c("Start","End"), 262, replace=T),
  value<- runif(262,20,40)
)
names(Data)[1] <- "Genotype"
names(Data)[2] <- "variable"
names(Data)[3] <- "value"

发生此错误是因为您试图将数值向量映射到 geom_errorbar 中的 dataGVW[1:64,3]ggplot 仅适用于 data.frame.

一般来说,您不应该在 ggplot 调用中进行子集化。您这样做是因为您的标准错误存储在四个单独的对象中。将它们添加到您的原始 data.frame 中,您将能够一次调用绘制所有内容。

这里有一个 dplyr 解决方案来汇总数据并预先计算标准误差。

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()