Was recently asked a question about how to organise the facets of a plot using a value. Specifically, (using mtcars
) taking the mean of hp
for each cyl
and gear
grouping and plotting the cyl
with the highest mean hp for 3-gear vehicles first. Successfully managed to create this graph:
But my code seemed a bit hacky, creating a new column:
mtcars %>%
group_by(gear) %>%
mutate(hp_gear3 = ifelse(gear == 3, hp, NA),
cyl = fct_reorder(factor(cyl),
hp_gear3,
mean,
na.rm = TRUE,
.desc = TRUE)) %>%
ggplot(aes(factor(gear), hp)) +
stat_summary(fun = mean) +
facet_wrap(~cyl)
I thought about using weighted.mean
instead inside of fct_reorder2()
, and this code gives the same output in fewer lines:
mtcars %>%
mutate(
cyl = fct_reorder2(factor(cyl),
hp,
gear==3,
weighted.mean,
.desc = TRUE)) %>%
ggplot(aes(factor(gear), hp)) +
stat_summary(fun = mean) +
facet_wrap(~cyl)
My intention here is to order each level of cyl
by weighting the mean gears conditional on 3-geared vehicles alone. It gives the right graph but I can't quite figure out whether it's doing what I'm asking it to, or just luckily landing in the right place. Am I understanding the working of fct_reorder2()
correctly?