I have tried the method from similar problems on this site but still have not been able to figure this out.
I'm using the titanic dataset from kaggle. The end result I am looking for is that within each Pclass factor, I want age.class (the bars) to be sorted from low to high by n. My attempt is below.
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)

