【问题标题】:How to change the order and labels of facets at the same time?如何同时更改构面的顺序和标签?
【发布时间】:2021-09-29 16:37:15
【问题描述】:

我想更改 ggplot2 图中构面的顺序和标签。我可以单独更改订单或标签,但不能同时更改它们。我跟着this line 更改顺序和this link 更改标签。有什么帮助吗?谢谢。

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

【问题讨论】:

  • 分面变量的名称已从 cat 更改为 "fct_relevel(cat, c('b', 'a')"。这很烦人,所以你可以改用labeller = as_labeller(label)
  • 嗨@teunbrand 它有效。您能否将您的解决方案发布为答案?我想选择它作为问题的答案。可能的进一步问题是,当facet_grid 有两个变量如facet_grid(var1 ~ var2) 时如何处理?

标签: r ggplot2 facet


【解决方案1】:

这应该可行:

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)) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    相关资源
    最近更新 更多