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?

Ryan
  • 1,048
  • 7
  • 14
  • Related: https://stackoverflow.com/questions/54178285/how-to-remove-only-some-facet-labels and https://stackoverflow.com/questions/45114850/only-show-one-variable-label-in-facet-wrap-strip-text – MrFlick Sep 17 '21 at 17:43

2 Answers2

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

MrFlick
  • 195,160
  • 17
  • 277
  • 295
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]))
             })
see24
  • 1,097
  • 10
  • 21