2

I'd like to change the order and labels of facets in a ggplot2 figure. I could change the order or labels separately, but could not change them at the same time. I followed this line to change the order and this link for labels. Any help? Thanks.

library(ggplot2)

df <- data.frame(x = seq(1, 8), y = seq(2, 9), cat = rep(c('a', 'b'), 4))

label <- c('label_1', 'label_2')
names(label) <- c('a', 'b')

df %>% 
  ggplot() +
  geom_line(aes(x = x, y = y)) +
  facet_grid(fct_relevel(cat, c('b', 'a')) ~., # change the order of facet
             labeller = labeller(cat = label)) # change the label of facet, failed
zx8754
  • 52,746
  • 12
  • 114
  • 209
just_rookie
  • 873
  • 12
  • 33
  • 2
    The name of the facetting variable has changed from cat to `"fct_relevel(cat, c('b', 'a')"`. This is annoying to type, so you can use `labeller = as_labeller(label)` instead. – teunbrand Jul 22 '21 at 11:50
  • Hi @teunbrand It works. Could you please post your solution as an answer? I'd like to select it as the answer to the question. And the possible further question is that how to deal with the situation when `facet_grid` has two variables like `facet_grid(var1 ~ var2)`? – just_rookie Jul 22 '21 at 12:01

1 Answers1

0

This should work:

library(ggplot2)
library(forcats)

df <- data.frame(x = seq(1, 8), y = seq(2, 9), cat = rep(c('a', 'b'), 4))
df1 <- df %>% 
  mutate(cat = fct_relevel(cat, c('b', 'a')),
         label = toupper(cat))

df1 %>% 
  ggplot() +
  geom_line(aes(x = x, y = y)) +
  facet_grid(cat ~., 
             labeller = labeller(cat = label)) 

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66