How to control which facet_wrap labels are displayed
Asked Answered
T

2

5

In the following use of facet_wrap, both the year and model are displayed in the plot labels.

library(tidyverse)
mpg %>%
  filter(manufacturer=='audi')%>%
  ggplot(aes(cty, hwy)) + 
  geom_point(aes(col = model)) +
  facet_wrap(year~model)

enter image description here

We already colored the points by model and it is shown in the legend, so we dont really need model in each facet label. How can we remove model from the labels?

Tricia answered 17/9, 2021 at 17:33 Comment(1)
Related: #54178785 and #45115350Melindamelinde
M
6

The easiest way would be to adjust the labeler function to only extract labels for the first variable. You can do that with

mpg %>%
  filter(manufacturer=='audi')%>%
  ggplot(aes(cty, hwy)) + 
  geom_point(aes(col = model)) +
  facet_wrap(~year+model, labeller=function(x) {x[1]})

The other way is to create an interaction variable so you are only faceting on one variable and then you can change the labeller to strip out the name of the second value. That would look like this

mpg %>%
  filter(manufacturer=='audi')%>%
  ggplot(aes(cty, hwy)) + 
  geom_point(aes(col = model)) +
  facet_wrap(~interaction(year,model), labeller=as_labeller(function(x) gsub("\\..*$", "", x)))

plot without model name in facet strip

Melindamelinde answered 17/9, 2021 at 17:49 Comment(0)
K
1

Another option is to define a custom labeller function. I found the explanation in the docs for "labellers" of what the input and output format needs to be a bit confusing. So hopefully this simple example helps others.

library(tidyverse)
mpg %>%
  filter(manufacturer=='audi')%>%
  ggplot(aes(cty, hwy)) + 
  geom_point(aes(col = model)) +
  facet_wrap(year~model, 
             labeller = function(df) {
               list(as.character(df[,1]))
             })
Killy answered 14/6, 2022 at 16:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.