Axis Order

Frequently you need to alter the order of the X or Y axis from the default (alphabetical) sort order. There are a few different ways to accomplish this based your specific needs

Using Forcats (tidyverse cool kids way)

The Forcats library is designed for managing factor levels.

Forcats Reorder: fct_reorder(<column_to_reorder>, <column_to_base_reorder_on>)  

# Default  order of X-axis based on alphabetical order of RG_PU
data %>% 

  ggplot(aes(x = RG_PU, y = Pct_Occupied, fill = as.factor(pM_Loaded))) + 

  geom_bar(stat = "identity")


# Reorder RG_PU by the Run_Start_Date

data %>% mutate(RG_PU = fct_reorder(RG_PU, Run_Start_Date)) %>% 

  ggplot(aes(x = RG_PU, y = Pct_Occupied, fill = as.factor(pM_Loaded))) + 

  geom_bar(stat = "identity")

Forcats Relevel: fct_relevel(<column_to_relevel>, order, list, explicit)  

# Default  order of X-axis based on alphabetical order of RG_PU
data %>% 

  ggplot(aes(x = RG_PU, y = Pct_Occupied, fill = as.factor(pM_Loaded))) + 

  geom_bar(stat = "identity")


# Reorder RG_PU by the Run_Start_Date

data %>% mutate(RG_PU = fct_relevel(RG_PU, "22KJFWLT4_1", "22KGLVLT4_1", "22KJFWLT4_2", "22KGLVLT4_2", "22KGLVLT4_3", "22KGLVLT4_4")) %>% 

  ggplot(aes(x = RG_PU, y = Pct_Occupied, fill = as.factor(pM_Loaded))) + 

  geom_bar(stat = "identity")

Forcing the Level Order (one of my old school ways)

Define a level order list and apply the order to the limits on scale_x_discrete()

# Set the order to prevent X-axis sorting by A-Z

level_order <- c('Patients', 'Female', 'Male','CLIA_Somatic', 'RUO_Genomes') 

scale_x_discrete(name = "", limits = level_order) +