在R中,处理Error:ggplot2不知道如何处理数字类的数据 [英] In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

查看:1968
本文介绍了在R中,处理Error:ggplot2不知道如何处理数字类的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to R and haven't done any programming before...

当我尝试创建一个带有标准误差条形图的盒子图时,我得到

When I attempt to create a box chart with standard error bars I get the error message mentioned in the title.

我使用了一个我在R Cookbook上找到的脚本,我稍微调整一下:

I used a script I found on R Cookbook which I tweaked a bit:

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 中的 data GVW [1:64,3] ggplot 只适用于 data.frame

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

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

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

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

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

这篇关于在R中,处理Error:ggplot2不知道如何处理数字类的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆