How to change the order and labels of facets at the same time?

Viewed 182

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
1 Answers

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

Related