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

时间:2019-04-03 21:04:01

标签: r ggplot2 facet-wrap

我正在尝试重命名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))

enter image description here

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

的“虚拟”列来进行一些排序
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))

enter image description here

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

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

但是,即使每个绘图中的数据正确,这也只会在两个构面之间重复第一个构面组

enter image description here

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

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

enter image description here

如何在彼此独立的多个facet_wrap()图中标记x轴刻度线?我觉得这里缺少一些基本的东西,但是我不知道是什么。

1 个答案:

答案 0 :(得分:2)

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

enter image description here