Created
July 20, 2019 00:01
Revisions
-
tomhopper renamed this gist
Jul 20, 2019 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
tomhopper created this gist
Jul 20, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,26 @@ # 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)