Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 670
erc Avatar asked Jan 14 '19 08:01

erc


2 Answers

It's not at all perfect, but I'll post this hoping is 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) 
like image 59
RLave Avatar answered Oct 07 '22 07:10

RLave


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

like image 1
TheAvenger Avatar answered Oct 07 '22 05:10

TheAvenger