【问题标题】:In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric在R中,处理错误:ggplot2不知道如何处理数字类的数据
【发布时间】:2018-01-29 06:01:46
【问题描述】:

我是 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"

【问题讨论】:

    标签: r class ggplot2


    【解决方案1】:

    发生错误是因为您试图将数字向量映射到 geom_errorbar:GVW[1:64,3] 中的 dataggplot 仅适用于 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()
    

    【讨论】:

    • 非常感谢 Scoa,数据现在按预期绘制。虽然,其中一个淘汰列丢失了,但我应该能够解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多