2

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?

Steven
  • 3,238
  • 21
  • 50
  • 2
    You could try `fct_reorder2` to reorder by both the category and the value. I find it pretty tricky to get exactly right, so you might need to mess around with it. I'd also recommend doing that rearranging *before* you try to plot so you can write it more clearly and verify it. You can then still pipe the rearranged data into `ggplot` the way you have here – camille Oct 30 '19 at 15:21
  • Also, this question might help if I'm imagining what you want correctly https://stackoverflow.com/q/31955729/5325862 – camille Oct 30 '19 at 15:23
  • @camille Thanks. I ended up `arrange()`ing the dataframe by `group, desc(prop)` then `mutate(rsk = rsk %>% factor(levels = unique(rsk)))` to get the appropriate order of `rsk` along the x-axis. I need to explore `fct_reorder2()` more. I've used `fct_reorder()` quite bit but never it's cousin. – Steven Oct 30 '19 at 16:29

0 Answers0