在多面 ggplot 中重命名有序的 x 轴标签

Rename ordered x-axis labels in faceted ggplot

我正在尝试重命名 ggplot() 中的多面、有序、x 轴刻度线。

library(ggplot2)
library(dplyr)
set.seed(256)

myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

n <- 15
dat <- data.frame(category = sample(letters[1:2], n, replace = T), 
                  name = myFun(n), 
                  perc = sample(seq(0, 1, by = 0.01), n, replace = TRUE))

to_plot <-
  dat %>% 
  group_by(category) %>%
  arrange(category, desc(perc)) %>%
  top_n(5, perc)

绘制这个让我兴奋

to_plot %>%
  ggplot(aes(x = name, y = perc)) +
  geom_bar(stat = "identity") +
  facet_wrap(~category, scales = "free_y") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

这是无序的,根本不是我想要的,所以我通过添加 row_number()

的 "dummy" 列来进行一些排序
to_plot %>%
  mutate(row_number = row_number()) %>%
  ungroup() %>%
  mutate(row_number = row_number %>% as.factor()) %>%
  ggplot(aes(x = row_number, y = perc)) +
  geom_bar(stat = "identity") +
  facet_wrap(~category, scales = "free_y") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

这让我很接近,但我仍然需要更改 x 轴上的名称,所以我添加:

  scale_x_discrete(name = "name", labels = str_wrap(to_plot %>% pull(name), 3))

但这只会在两个方面重复第一个方面组,即使每个图中的数据都是正确的

我也试过按顺序排列所有东西并允许两个轴在 facet_wrap() fx 中都是 free,但这似乎也不起作用:

new_plot <- 
  dat %>% 
  group_by(category) %>%
  arrange(category, desc(perc)) %>%
  ungroup() %>%
  mutate(row_number = row_number() %>% as.factor())


new_plot %>% 
  ggplot(aes(x = row_number, y = perc)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "name", labels = new_plot %>% pull(name)) +
  facet_wrap(~category, scales = "free") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

如何在多个 facet_wrap() 绘图中相互独立地标记 x 轴刻度线?我觉得我在这里遗漏了一些非常基本的东西,但我不知道它是什么。

to_plot %>%
  ggplot(aes(x = name %>% forcats::fct_reorder(-perc), y = perc)) +
  geom_bar(stat = "identity") +
  facet_wrap(~category, scales = "free") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))