Search code examples
rggplot2geom-barstacked-chart

Reverse the order of a stacked bar chart in ggplot


I'm doing a sales analysis, to see how many sales occured in different time periods. This is my code:

mutate(
    g = ifelse(Diff_l_b < 720 & Diff_l_b > 360, -1, 
    ifelse(Diff_l_b < 360 & Diff_f_b > 270, 1,
    ifelse(Diff_f_b < 270 &  Diff_f_b > 90, 2,
    ifelse(Diff_f_b < 90,3, NA_real_))))
)   
ggplot(data = T_AD,
       aes(x = `Name Sales Representative`, y = g ))+
        geom_bar(stat = "identity", aes(fill = as.factor(g)))
        scale_fill_discrete(
          name = "Veterinarians Sold To", 
          labels = c("2 years ago", "last year", "last 9 month","last 3 month" ))+
        ggtitle( "Actica25")+
        ylab("Veterinarians Sold To") +
        coord_flip() 

and it shoud look like this:

Graph

but the order of stacking should be reversed.

I tried already with fct_rev, relevel and order but every time I define g as factor before plotting it turns out like this.

So the "last year" part should be on the inside and "9 month" on its right an "last 3 month" right of that one. Thanks for the help.


Solution

  • You did not provide an example of your data, however if you just need to reverse stacked bars in your plot, you can use:

    position = position_stack(reverse = TRUE)
    

    inside your geom_bar() or geom_col() function, so for example:

    geom_bar(position = position_stack(reverse = TRUE), aes(fill = g))
    

    See more info in documentation.

    If you need to flip your legend, use:

    guides(fill = guide_legend(reverse = TRUE))
    

    as a part of your ggplot, like:

    ... +
    ggtitle( "Actica25") +
    ylab("Veterinarians Sold To") +
    coord_flip() +
    guides(fill = guide_legend(reverse = TRUE))
    

    See more details in documentation.