-2

I am trying to represent my data as box plots and my data frame currently looks as follows:

  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

I run the following script and produce a figure with species (V4) as the x-axis, total length (V2) as the y-axis, ordered by V2, and colored by 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

The problem is that when I then run

box + facet_grid(. ~ V5)

The goal is to create two plots separated by sex (V3), but it does not work. I get the following error:

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

I can provide the full data set if needed.

Any help would be great! Thanks, Steven M.

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • here is a link to the whole data set: https://www.dropbox.com/sh/yrw1rhr88q5a07t/AABpGsQp7efVoCfLeyFnxoE6a?dl=0 – Steven Messer Jun 14 '17 at 23:07
  • 3
    Your example code and example plot don't match up. There is no column named Condition in your example data and you used V5 in the `facet_grid` when sex is V3. I don't think that's causing the error, but it's difficult to answer when the question contains conflicting data. – neilfws Jun 14 '17 at 23:13
  • Please check your question carefully and provvide all the elements to work on it. – Al14 Jun 14 '17 at 23:25

2 Answers2

3

This works fine for me using your complete dataset.

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)

enter image description here

neilfws
  • 32,751
  • 5
  • 50
  • 63
0

Here is another example from your sample data

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

Tuyen
  • 977
  • 1
  • 8
  • 23