Search code examples
rdatabaseggplot2facet

Removing Empty Facet Categories


Am having trouble making my faceted plot only display data, as opposed to displaying facets with no data.

The following code:

p<- ggplot(spad.data, aes(x=Day, y=Mean.Spad, color=Inoc))+
    geom_point()

p + facet_grid(N ~ X.CO2.)

Gives the following graphic: enter image description here

I have played around with it for a while but can't seem to figure out a solution.

Dataframe viewable here: https://docs.google.com/spreadsheets/d/11ZiDVRAp6qDcOsCkHM9zdKCsiaztApttJIg1TOyIypo/edit?usp=sharing

Reproducible Example viewable here: https://docs.google.com/document/d/1eTp0HCgZ4KX0Qavgd2mTGETeQAForETFWdIzechTphY/edit?usp=sharing


Solution

  • Your issue lies in the missing observations for your x- and y variables. Those don't influence the creation of facets, that is only influenced by the levels of faceting variables present in the data. Here is an illustration using sample data:

    #generate some data
    nobs=100
    set.seed(123)
    dat <- data.frame(G1=sample(LETTERS[1:3],nobs, T),
                      G2 = sample(LETTERS[1:3], nobs, T),
                      x=rnorm(nobs),
                      y=rnorm(nobs))
    #introduce some missings in one group
    dat$x[dat$G1=="C"] <- NA
    
    #attempt to plot
    p1 <- ggplot(dat, aes(x=x,y=y)) + facet_grid(G1~G2) + geom_point()
    p1 #facets are generated according to the present levels of the grouping factors
    

    enter image description here

    #possible solution: remove the missing data before plotting
    p2 <- ggplot(dat[complete.cases(dat),], aes(x=x, y=y)) + facet_grid(G1 ~G2) + geom_point()
    p2
    

    enter image description here