Search code examples
rggplot2facet-wrap

How to remove only some facet labels?


Using facet_wrap, is it possible to remove only some facet labels? In the following example I'd like the Species label to only appear in the first column of each row. I know I can use the labeller function but not how to change individual labels.

data(iris)
library(tidyr)
library(ggplot2)

dat <- iris %>%
  gather(var, val, Sepal.Length:Petal.Width) 

ggplot(dat) +
  geom_point(aes(x = 1, y = val)) +
  facet_wrap(Species~var)

enter image description here


Solution

  • It's not at all perfect, but I am posting this hoping it's still better than nothing.

    The use of as_labeller() and labeller() may get you what you need.

    Update

    Easiest solution was to split Species and var in two labellers functions.

    facet_labeller_top <- function(variable, value) {
      c(
        "Setosa", 
        "",
        "",
        "",
        "Versicolor", 
        "",
        "",
        "",
        "Virginica", 
        "",
        "",
        ""
      )
    }
    
    facet_labeller_bottom <- function(variable, value) {
      c(
        "Petal.Length", 
        "Petal.Width",
        "Sepal.Length",
        "Sepal.Width",
        "Petal.Length", 
        "Petal.Width",
        "Sepal.Length",
        "Sepal.Width",
        "Petal.Length", 
        "Petal.Width",
        "Sepal.Length",
        "Sepal.Width"
      )
    }
    

    Result:

    ggplot(dat) +
      geom_point(aes(x = 1, y = val)) +
      facet_wrap(Species~var, labeller = labeller(Species=as_labeller(facet_labeller_top),
                                                  var = as_labeller(facet_labeller_bottom)))
    

    enter image description here

    Data example:

    library(tidyr)
    library(ggplot2)
    
    dat <- iris %>%
      gather(var, val, Sepal.Length:Petal.Width)