Skip to content

Instantly share code, notes, and snippets.

@tomhopper
Created July 20, 2019 00:01
Show Gist options
  • Save tomhopper/26b3b50f99b9a20f61be8b663d874f44 to your computer and use it in GitHub Desktop.
Save tomhopper/26b3b50f99b9a20f61be8b663d874f44 to your computer and use it in GitHub Desktop.
Sort a grouping variable by a second numeric variable, in the presence of a faceting variable
# Sort a grouping variable by a second numeric variable, in the presence of a faceting variable
# Ostensibly so that the grouping variable plots in ascending (or descending) order of the
# central tendency of the numeric variable.
library(tidyverse)
# Create a dataset
set.seed(10001)
my_df <- tibble(facet_var = rep(letters[1:4], each = 5*10),
group_var = rep(rep(letters[13:17], each = 10), times = 4),
group_shift = rep(rep(runif(5, min = 1, max = 5), each = 10), times = 4),
value = runif(4*5*10, min = 20, max = 40) + group_shift)
set.seed(NULL)
# Sort the grouping variable
# This approach entirely within tidyverse
my_df <- my_df %>%
mutate(group_var = as.factor(group_var)) %>%
group_by(facet_var) %>%
mutate(group_var = fct_reorder(.f = group_var, .x = value,.fun = median))
# And plot
my_df %>%
ggplot(aes(x = group_var, y = value, color = group_var)) +
geom_boxplot() +
facet_wrap(.~facet_var)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment