Search code examples
rggplot2forcats

Order categories in ggplot


Problem

I would like to know how I could use fct_recode to reorder the position of variables in a geom_col plot. The aim is to order from greatest to least, bottom to top based on the Australian values.

enter image description here

My attempt

ggplot(data = df, aes(x = country, y = value, fill = fct_recode(chart_type, value)) + 
  geom_col()

Data

structure(list(country = c("Australia", "Australia", "Australia", 
"Australia", "Australia", "Australia", "Australia", "Australia", 
"Australia", "Australia", "Australia", "Australia", "Australia", 
"Australia", "Australia", "Australia", "Australia", "Australia", 
"Australia", "OECD - Average", "OECD - Average", "OECD - Average", 
"OECD - Average", "OECD - Average", "OECD - Average", "OECD - Average", 
"OECD - Average", "OECD - Average", "OECD - Average", "OECD - Average", 
"OECD - Average", "OECD - Average", "OECD - Average", "OECD - Average", 
"OECD - Average", "OECD - Average", "OECD - Average", "OECD - Average"
), value = c(11.314258, 4.572229, 0, 0, 1.356282, 1.665903, 0, 
0, 1.330865, 0, 0, 3.57475, 0.086851, 0, 2.786991, 0, 1.069969, 
0, 0, 8.239819, 2.865435, 0.241395, 9.160657, 0.400194, 1.102444, 
0.167023, 0.12324, 0.435496, 0.051199, 0.012553, 6.792114, 0.120639, 
0.073286, 3.288726, 0.002667, 0.6529, 0.043262, 0.157044), chart_type = c("Income tax", 
"Corporation tax", "Other taxes", "SSC's + payroll tax", "SSC's + payroll tax", 
"Recurrent building taxes", "Other taxes on property/capital", 
"Other taxes on property/capital", "Other taxes on property/capital", 
"Other taxes on property/capital", "Other taxes on property/capital", 
"VAT and GST", "VAT and GST", "Other indirect taxes", "Other indirect taxes", 
"Other indirect taxes", "Other indirect taxes", "Other indirect taxes", 
"Other taxes", "Income tax", "Corporation tax", "Other taxes", 
"SSC's + payroll tax", "SSC's + payroll tax", "Recurrent building taxes", 
"Other taxes on property/capital", "Other taxes on property/capital", 
"Other taxes on property/capital", "Other taxes on property/capital", 
"Other taxes on property/capital", "VAT and GST", "VAT and GST", 
"Other indirect taxes", "Other indirect taxes", "Other indirect taxes", 
"Other indirect taxes", "Other indirect taxes", "Other taxes"
)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-38L))

Solution

  • Do you mean something like this?

    library(dplyr)
    library(ggplot2)
    
    df %>%
      arrange(country, desc(value)) %>%
      mutate(chart_type = factor(chart_type, levels = rev(unique(chart_type)))) %>%
      ggplot() + aes(country, value, fill = chart_type) + geom_col()
    

    enter image description here