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

问题描述 投票:1回答:1

我正在尝试重命名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轴刻度线?我觉得我在这里遗漏了一些非常基本的东西,但我无法弄清楚它是什么。

r ggplot2 facet-wrap
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.