如何使用2个因素订购GEOM_COL图的X轴?
我已经尝试了此站点上类似问题的方法,但仍然无法弄清楚这一点。
我正在使用Kaggle的泰坦尼克号数据集。我要寻找的最终结果是,在每个PCLASS因子中,我希望Age.Class(bars)从低到高排序的n。我的尝试在下面。
library(tidyverse)
library(titanic)
df <- titanic::titanic_train
head(df)
# Start -------------------------------------------------------------------
df = df %>%
mutate(has.cabin = if_else(Cabin == '', 0, 1) %>% as.factor(),
Pclass = Pclass %>% as.factor(),
age.class = case_when(
Age < 5 ~ 'baby',
Age >5 & Age < 12 ~ 'Child',
Age > 12 & Age < 18 ~ 'Teen',
Age > 18 & Age < 25 ~ 'Young Adult',
Age > 25 & Age <35 ~ 'Mid Adult',
Age > 35 & Age < 60 ~ 'Adult',
Age > 60 ~ 'Elderly',
TRUE ~ 'Undefined'
)
)
plot.data = df %>% count(has.cabin, Pclass, age.class)
lvls <- unique(plot.data$Pclass[order(plot.data$age.class,-plot.data$n)])
plot.data$age.classv2 = factor(plot.data$age.class, levels=lvls)
plot.data %>%
ggplot(., aes(x = Pclass, y = n, fill = age.class)) +
geom_col(position = 'dodge') +
facet_grid(~ has.cabin)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道一种简单的方法可以在方面内的一个因素内订购因素。有函数
forcats :: fct_reorder
重新排序因子tidytext :: reorder_within
在一个方面重新排序一个因子,我使用了第二个因子,我使用了第二个因素,并由
pclass进行了。
和2个图,一个用于has.cabin == 0
,一个用于has.cabin == 1
和之后将它们缝合在一起。一个人需要一个单独的变量,用于
填充
参数,因为内部,reorder_within
在附加的facet名称上生成了几个变量。如果您不使用额外的变量,则会看到这些名称,请参阅。由 reprex软件包(v1.0.0)
我想为了重新订购一个因素,一个因素需要调整
reorder_within
。I don't know of an easy way to order factors within a factor within facets. There are the functions
forcats::fct_reorder
to reorder factorstidytext::reorder_within
to reorder one factor within a facetI've used the second one and faceted by
Pclass
and made 2 plots, one forhas.cabin == 0
and one forhas.cabin == 1
and afterwards stitched them together.One need a separate variable for the
fill
argument because internally,reorder_within
generates several variables with the facet name appended. If you don't use the extra variable, then you see these names, see the comments in Julia Silge's blog.Created on 2022-06-30 by the reprex package (v1.0.0)
I think in order to reorder a factor within a factor within a facet one would need to adapt
reorder_within
.