with data
dat <-
structure(list(group = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
.Label = c("alwaysFirst", "last"),
class = "factor"),
rsk = structure(c(3L,1L, 2L, 4L, 3L, 1L, 2L, 4L),
.Label = c("beginning", "middle", "startsWithS", "zed"),
class = "factor"),
prop = c(0.47, 0.38, 0.15, 0.54, 0.14, 0.78, 0.64, 0.36)),
class = "data.frame",
row.names = c(NA, -8L))
I can group and reorder a geom_bar()
with
dat %>%
ggplot(aes(x = rsk %>% fct_reorder(-prop), y = prop, fill = group)) +
geom_bar(stat = "identity", position = "dodge")
This reorders based on the default .fun = median
in the fct_reorder()
statement. This is great, but when I'm also dealing with a fill
in aes()
, I'd like to force the fct_reorder
to use only one of the fill
values to reorder the plot.
In other words, for the data above, I'd like the plot to be in x-axis order of: zed
, startsWithS
, beginning
, middle
, the descending order based upon the ordering of the prop
values where group == "alwaysFirst"
. I can hardcode the reordering of the values with the levels
argument of factor()
(as in this question) but I'd rather let ggplot
do it, if possible, especially as this could change with different groups.
How can I force ggplot
to reorder the x
values based only on one of the groups in the fill
argument?