Search code examples
rsortingggplot2bar-chartstacked

Sort x-axis for proportional stacked barplot in ggplot


I have a data set like this:

df <- data.frame(
  sample = c("s1", "s1", "s1", "s2", "s2", "s3", "s3", "s3", "s4", "s5", "S5", "S5", "S6", "S7", "S8", "S8", "S8", "S9", "S9", "S9"),
  ploidy = c(3, 4, 2, 3, 4, 2, 3, 4, 2, 2, 3, 4, 3, 4, 2, 3, 4, 2, 3, 4),
  freq = c(0.3, 0.4, 0.3, 0.8, 0.2, 0.6, 0.3, 0.1, 1.0, 0.7, 0.2, 0.1, 1.0, 1.0, 0.4, 0.1, 0.5, 0.1, 0.1, 0.8)
)

It may not be difficult to generate stacked barplot like this:

enter image description here

But i need to make it more elegant, it would be perfect if i can sort the x-axis based on the decreasing order of proportion of ploidy 4 for each sample. for the samples have no ploidy 4, just order them alphabetically.

Highly appreciate if anyone could help!


Solution

  • Use arrange and forcats::fct_inorder to set the order you want

    
    df %>% 
      mutate(perc = freq/sum(freq), .by = sample) %>% 
      arrange(desc(ploidy), desc(perc)) %>% 
      mutate(sample = forcats::fct_inorder(sample)) %>% 
      ggplot(aes(x = sample, y = perc)) +
      geom_col(aes(fill = as.factor(ploidy)))
    

    Created on 2023-04-18 with reprex v2.0.2