如何通过排列数据框来操纵绘图的顺序

How to manipulate the order of a plot by arranging the data frame

通常当我想重新排序例如条形图时,我在 ggplot 轴上使用 reorder() 函数。现在这是一个选项,但在 coord_flip() 之后有时会让我感到困惑,我真的不喜欢这种做事方式。我宁愿操纵数据本身。

我的数据框:

library(tidyverse)

warCasualties <- tibble(Who = c("N. Vietnam + communist allies",
               "South Vietnam",
               "Vietnamese civilians",
               "United States",
               "Allied forces"),
       Type = c("Military",
                "Military",
                "Civilians",
                "Military",
                "Military"),
       Estimated.deaths = c((950765 + 1100000)/2,
                            (110000 + 313000)/2,
                            2000000,
                            58220,
                            5341)) 

我想执行以下操作,但我的绘图不会像数据框那样排序。

warCasualties %>%
  arrange(desc(Estimated.deaths)) %>%
  ggplot(aes(x = Estimated.deaths, y = Who)) +
  geom_segment(aes(x = 0, y = Who, xend = Estimated.deaths, yend = Who)) +
  geom_point() 

您可以使用包 forcats 的功能 fct_inorder(),它将因子的水平设置为它们在您排列的小标题中出现的顺序。 ggplot() 正在寻找一个因子变量来确定轴顺序,如果它不是一个因子,它将与 as.factor()(静默地)产生您所看到的字母顺序相一致。

library(forcats)

warCasualties %>%
    arrange(desc(Estimated.deaths)) %>%
    mutate(Who = forcats::fct_inorder(Who)) %>%
    ggplot(aes(x = Estimated.deaths, y = Who)) +
    geom_segment(aes(x = 0, y = Who, xend = Estimated.deaths, yend = Who)) +
    geom_point() 

我不确定为什么 forcats 没有加载 tidyverse。这将是一个很好的补充,因为它有一些很好的因子工具,而且它是由 Hadley and Co. 构建的。

这个基本解决方案怎么样:

  ggplot(warCasualties,aes(x = Estimated.deaths, y = reorder(Who, -Estimated.deaths))) +
  geom_segment(aes(x = 0, y = reorder(Who, -Estimated.deaths), xend = Estimated.deaths, yend = Who)) +
  geom_point() 

使用 reorder(Who, -Estimated.deaths) 让 Who 从高到低排序。