繁体   English   中英

如何通过排列数据框来控制图的顺序

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

通常,当我想对条形图进行重新排序时,我会在ggplot轴上使用reorder()函数。 现在这是一个选项,但是有时在coord_flip()之后使我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() ,该函数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)使reorder(Who, -Estimated.deaths)排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM