Search code examples
rggplot2legendgeom-bar

Reorder Columns/Legend


Country_Of_Data Year  Appr_Country Apprehension
##    <chr>           <chr> <chr>       <dbl>
##  1 Afghanistan     2010  PAN          17
##  2 Afghanistan     2011  PAN           0
##  3 Afghanistan     2010  MEX           3
##  4 Afghanistan     2011  MEX           4
##  5 Afghanistan     2010  US            0
##  6 Afghanistan     2011  US            19
ggplot(Afghan_Appr, aes(Year, Apprehension, fill = Appr_Country)) + geom_bar(stat = "identity", position = 'dodge')

enter image description here My outputted plot basically plots three bars per each year but does it in the order of MEX, PAN, US when I want it to be PAN, MEX, US. Is there a way to switch the order? I tried using Afghan$Appr_Country to switch the order, but because of the structure of the data it doesn't work.


Solution

  • Use fct_relevel from forcats package to switch the order of the df

    library(ggplot2)
    library(forcats)
    
    ggplot(Afghan_Appr, aes(x = Year, y = Apprehension, fill = fct_relevel(Appr_Country, c("PAN", "MEX", "US")))) +
      geom_bar(stat = "identity", position = "dodge")