Search code examples
rggplot2facet-wrap

Reordering by x bar using one value of facet variable


For the dataset below, I'd like to customize my below plot by ordering states according to the total number of deaths experienced by age 65. I tried the below code.

The answer here does not answer my question because my x variables include 50 values whereas the response is helpful for variables with a few values.

Thanks,

NM

Here is my data:

CAPS_2019 <- structure(list(Age = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
2L, 3L), .Label = c("30", "50", "65"), class = "factor"), Dx = c(3.057, 
7.847, 17.157, 2.851, 8.861, 21.885, 2.521, 7.889, 21.328), PopName = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("AK", "AL", "AR"), class = "factor")), row.names = c(NA, 
-9L), class = c("tbl_df", "tbl", "data.frame"))

My code:

CAPS_plot_facet <- CAPS_2019 %>% 
  ggplot(aes(x = reorder(PopName, Dx), y = Dx, fill = factor(as.character(Age)))) +
  geom_col(position = position_stack(reverse = TRUE)) +
  facet_wrap("Age",scales="free_x")+
  theme_classic()+
  theme(strip.background = element_blank(), strip.text = element_blank())+
  coord_flip()+
  labs(x = "State", y = "Deaths (%)", caption = (""), face = "bold", fill = "Age")
CAPS_plot_facet 

My plot:

enter image description here


Solution

  • @RobertoT's answer discusses how to sort by Age and Dx. If you want to do that inline using dplyr::arrange and forcats::fct_inorder:

    Reorder by Age and Dx

    library(dplyr)
    library(forcats)
    
    CAPS_2019 %>% 
      arrange(desc(Age), desc(Dx)) %>% 
      ggplot(aes(x = fct_inorder(PopName), y = Dx, fill = factor(as.character(Age)))) +
      geom_col(position = position_stack(reverse = TRUE)) +
      facet_wrap("Age",scales="free_x")+
      theme_classic()+
      theme(strip.background = element_blank(), strip.text = element_blank())+
      coord_flip()+
      labs(x = "State", y = "Deaths (%)", caption = (""), face = "bold", fill = "Age")
    



    Reorder specifically by Dx at Age 65

    If you want to specifically sort by Deaths for Age 65 (per the submission's question), you can do the following:

    library(dplyr)
    library(forcats)
    
    CAPS_2019 %>% 
      group_by(PopName) %>%
      mutate(Dx_Age65 = Dx[Age == 65]) %>%
      ggplot(aes(x = fct_reorder(PopName, Dx_Age65, .desc = TRUE), y = Dx, fill = factor(as.character(Age)))) +
      geom_col(position = position_stack(reverse = TRUE)) +
      facet_wrap("Age",scales="free_x")+
      theme_classic()+
      theme(strip.background = element_blank(), strip.text = element_blank())+
      coord_flip()+
      labs(x = "State", y = "Deaths (%)", caption = (""), face = "bold", fill = "Age")