【问题标题】:Move empty factor levels while maintaining order of non-empty levels in ggplot2移动空因子水平,同时保持 ggplot2 中非空水平的顺序
【发布时间】:2021-04-27 16:03:17
【问题描述】:

我正在尝试使用按因子水平计算的值制作 ggplot2 列图。我希望创建一个图,其中空因子水平显示在图上,但保留在轴的底部。目前,他们处于领先地位。我已经根据计算值重新排序了我的因子,并希望为它们保留它。我将包括示例数据。

library(tidyverse)
data(mtcars)

mtcars %>%
  mutate(cyl = as.factor(cyl),
    cyl = fct_expand(cyl, c("2", "4", "6", "8"))) %>%
  group_by(cyl) %>%
  summarize(meanMPG = mean(mpg)) %>%
  ungroup() %>%
  mutate(cyl = fct_reorder(cyl, meanMPG)) %>%
  ggplot(aes(x = cyl, y = meanMPG)) +
  geom_col() +
  scale_x_discrete(drop = FALSE) +
  coord_flip() # shows empty level "2" on the top

【问题讨论】:

  • 所以您希望图表按 4、6、8 和 2 的顺序排列(因为它是空的)?
  • @dash2 是的!确切地。我应该提到我的实际数据框是在一个函数中编程的,所以我需要在不提前知道哪些因子级别为空的情况下执行此操作

标签: r ggplot2


【解决方案1】:

这出人意料地棘手 - 鉴于您需要做的就是正确排列关卡。我在forcats 中找不到任何直接合适的内容,但我们可以编写自己的重新排序函数。

my_reorder <- function (fac, var) {
  fac <- fct_reorder(fac, {{var}})
  l <- levels(fac)
  nonempty <- levels(factor(fac)) # I got this idea from droplevels()
  empty <- setdiff(l, nonempty)
  fct_relevel(fac, empty, nonempty)
  fct_relevel(fac, empty, nonempty)
}

mtcars %>%
  mutate(cyl = as.factor(cyl),
         cyl = fct_expand(cyl, c("2", "4", "6", "8"))) %>%
  group_by(cyl) %>%
  summarize(meanMPG = mean(mpg)) %>%
  ungroup() %>%
  mutate(cyl = my_reorder(cyl, meanMPG)) %>%
  ggplot(aes(x = cyl, y = meanMPG)) +
  geom_col() +
  scale_x_discrete(drop = FALSE, ) +
  coord_flip() # shows empty level "2" on the top

【讨论】:

  • 这是一个祝福。非常感谢。
【解决方案2】:

我们可以在group_by中使用.drop = FALSE

library(dplyr)
library(ggplot2)
library(forcats)
mtcars %>% 
  group_by(cyl = fct_expand(as.factor(cyl), c('2', '4', '6', '8')), 
     .drop = FALSE) %>%
  summarize(meanMPG = mean(mpg), .groups = 'drop') %>% 
  arrange(!is.na(meanMPG), meanMPG) %>% 
  mutate(cyl = factor(cyl, levels = cyl)) %>% 
  ggplot(aes(x = cyl, y = meanMPG)) +
    geom_col() + 
    scale_x_discrete(drop = FALSE) +
    coord_flip()

-输出

【讨论】:

  • 这对于降低“2”级很有用,但我想保留它并将其移动到轴的末端
猜你喜欢
  • 1970-01-01
  • 2018-12-07
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 2014-09-29
  • 2012-07-20
相关资源
最近更新 更多