【问题标题】:Rename ordered x-axis labels in faceted ggplot重命名多面ggplot中的有序x轴标签
【发布时间】:2019-08-25 12:26:51
【问题描述】:

我正在尝试重命名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() 的“虚拟”列进行一些排序

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 轴刻度线?我觉得我在这里遗漏了一些非常基本的东西,但我不知道它是什么。

【问题讨论】:

    标签: r ggplot2 facet-wrap


    【解决方案1】:
    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))
    

    【讨论】:

    • 如果您遇到过相同名称出现在多个方面的情况,但您仍想在每个方面进行排序,这里有一个解决方案:drsimonj.svbtle.com/ordering-categories-within-ggplot2-facets
    • 我知道这很简单。谢谢。
    • 附录:tidytext::reorder_within() 是处理特定方面排序的一种很好的自动方式。
    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2018-05-19
    • 2016-03-18
    • 2016-05-07
    • 2019-04-03
    • 2020-12-30
    • 2014-01-01
    相关资源
    最近更新 更多