Home > Net >  ggplot facet different Y axis order based on value
ggplot facet different Y axis order based on value

Time:05-08

I have a faceted plot wherein I'd like to have the Y-axis labels and the associated values appear in descending order of values (and thereby changing the order of the labels) for each facet. What I have is this, but the order of the labels (and the corresponding values) is the same for each facet.

ggplot(rf,
       aes(x = revenues, 
           y = reorder(AgencyName, revenues)))  
  geom_point(stat = "identity", 
           aes(color = AgencyName),
           show.legend = FALSE)  
  
  xlab(NULL)   
  ylab(NULL)   
  scale_x_continuous(label = scales::comma)  
  facet_wrap(~year, ncol = 3, scales = "free_y")   
  theme_minimal()

Can someone point me to the solution?

CodePudding user response:

The functions reorder_within and scale_*_reordered from the tidytext package might come in handy.

reorder_within recodes the values into a factor with strings in the form of "VARIABLE___WITHIN". This factor is ordered by the values in each group of WITHIN. scale_*_reordered removes the "___WITHIN" suffix when plotting the axis labels. Add scales = "free_y" in facet_wrap to make it work as expected.

Here is an example with generated data:

library(tidyverse)

# Generate data
df <- expand.grid(
  year = 2019:2021,
  group = paste("Group", toupper(letters[1:8]))
)
set.seed(123)
df$value <- rnorm(nrow(df), mean = 10, sd = 2)

df %>% 
  mutate(group = tidytext::reorder_within(group, value, within = year)) %>% 
  ggplot(aes(value, group))  
  geom_point()  
  tidytext::scale_y_reordered()  
  facet_wrap(vars(year), scales = "free_y")
  • Related