Hi all!
I'm trying to sort a factor variable in a plot, using forcats and ggplot2. However, since I have two values of the value I want to sort by for each factor level, it is sorted by the mean of those values, see the example below. I know that I can change to the max, using .fun = "max"
, but it doesn't lead to the result I want. I want to sort by just one of values (where group == a), i.e., in the example below, I want to sort the months by the values in group a, and only if the value is the same in a for two months, I want to sort by the value in b. In other words, I want the red dots to be sorted from higher to lower values.
Any suggestions on how I can accomplish this? Any help would be greatly appreciated.
Best, R
library(tidyverse)
df <- tibble(month = rep(month.name, each = 2),
group = rep(c("a","b"), 12),
value = rnorm(24))
df |>
mutate(month = fct_reorder(month, value)) |>
ggplot(aes(value, month, color = group)) +
geom_point(position = position_dodge(.5))
Created on 2023-11-13 with reprex v2.0.2