我跟着例子,我不能让facet_grid工作拆分我的数据

问题描述:

我想代表我的数据箱线图,我的数据帧目前看起来如下:我跟着例子,我不能让facet_grid工作拆分我的数据

V1 V2  V3   V4  V5 
1 1 12.18 FEMALE A_ambiguus  Host 
2 2 11.81 FEMALE A_ambiguus  Host 
3 3 10.70 MALE A_ambiguus  Host 
4 4 11.07 MALE A_ambiguus  Host 
5 5 7.95 FEMALE A_ameliae Parasite 
6 6 7.42 FEMALE A_ameliae Parasite 

我运行下面的脚本并生成一个以X轴为物种(V4),Y轴为总长(V2),V2命令并以V5着色的图形。

box <- ggplot(TL_sub, aes(x = V4, y = V2, group = V4)) + 
    scale_y_continuous(name = "TL (mm)") + 
    theme(axis.text.x=element_text(angle = 45, hjust = 1)) + 
    geom_boxplot(aes(fill=Condition)) + 
    aes(x=reorder(V4,V2),y=V2,label=TL) 

box 

Sorted boxplot of all data

的问题是,当我再运行

box + facet_grid(. ~ V5) 

的目标是要建立按性别(V3)分隔的两个地块,但它不能正常工作。我收到以下错误:

Error in combine_vars(data, params$plot_env, cols, drop = params$drop) : 
    At least one layer must contain all variables used for facetting 

如果需要,我可以提供完整的数据集。

任何帮助将是伟大的! 谢谢, Steven M.

+0

另一个例子这里是一个链接到整个数据集: HTTPS://www.dropbox。 com/sh/yrw1rhr88q5a07t/AABpGsQp7efVoCfLeyFnxoE6a?dl = 0 –

+3

您的示例代码和示例图不匹配。在您的示例数据中没有名为Condition的列,并且当sex为V3时,您在'facet_grid'中使用了V5。我不认为这是导致错误的原因,但当问题包含冲突数据时很难回答。 – neilfws

+0

请仔细检查您的问题,并提供所有的元素来处理它。 – Al14

这适用于我使用完整的数据集。

TL_subset %>% 
    ggplot(aes(reorder(Species, TL), TL)) + 
    geom_boxplot(aes(fill = Condition)) + 
    labs(x = "Species", y = "TL (mm)") + 
    theme(axis.text.x = element_text(angle = 45, hjust = 1)) + 
    facet_grid(. ~ Sex) 

这里是您的样本数据

dataset<-data.frame(V2=c(12.18,11.81,10.70,11.07,7.95,7.42), 
        V3=c("FEMALE","FEMALE","Male","Male","FEMALE","FEMALE"), 
        V4=c("A_ambiguus","A_ambiguus","A_ambiguus","A_ambiguus","A_ameliae","A_ameliae"), 
        V5=c("Host","Host","Host",'Host',"Parasite","Parasite"))     


library(ggplot2) 

ggplot(data=dataset,aes(x=V4,y=V2)) + geom_boxplot(aes(fill=V5))+facet_grid(.~V3) +xlab("Species") + 
    ylab("TL (mm)") + scale_fill_discrete(name="Condition") 

enter image description here