12

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

erc
  • 10,113
  • 11
  • 57
  • 88

2 Answers2

9

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) 
RLave
  • 8,144
  • 3
  • 21
  • 37
  • Why would I see this error: `Error in labeller(Species = as_labeller(facet_labeller_top), var = as_labeller(facet_labeller_bottom)) : unused arguments (Species = as_labeller(facet_labeller_top), var = as_labeller(facet_labeller_bottom))`? – CrunchyTopping Sep 09 '19 at 15:49
  • 1
    Which version of `ggplot2` are you on? On `3.2.1` currently works. Try with a clean env if it still fails for you. – RLave Sep 10 '19 at 07:16
  • 1
    Thanks! It was a version issue, updating solved it. – CrunchyTopping Sep 10 '19 at 12:12
1

I don't know if I understand well but I will try:

You can use facet_grid instead of facet_wrap

this is the code:

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_grid(Species~var)

This is the result: enter image description here

TheAvenger
  • 458
  • 1
  • 6
  • 19
  • 4
    Thanks, but this is not what I want. As I said, I want the Species label to appear only in the first column of each row of facets. – erc Jan 14 '19 at 09:08