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