Search code examples
rggplot2forcats

Order levels of a factor in a guide and on the axis of a flipped barchart


Hi there: Is there a way to modify the plot below so that the factor 'C' is displayed on top? i.e. I'd like the order of the factors on the (flipped) y-axis to mirror the order of them displayed in the legend.

var1<-sample(c('A', 'B', 'C'), replace=T, size=100)
var2<-sample(c('apples', 'bananas'), replace=T, size=100)
var3<-rnorm(100, mean=100)
df<-data.frame(var1, var2, var3)

df %>% 
  mutate(var1=fct_reorder(var1, var3, mean)) %>% 
  ggplot(., aes(y=var1, x=var3, fill=var1))+facet_wrap(~var2)+geom_col()+scale_fill_grey()

Solution

  • You can use scale_y_discrete(limits = rev) :

    library(dplyr)
    library(ggplot2)
    library(forcats)
    
    df %>% 
    mutate(var1=fct_reorder(var1, var3, mean)) %>% 
    ggplot(., aes(y=var1, x=var3, fill=var1)) + 
    facet_wrap(~var2)+
    geom_col()+
    scale_fill_grey() +
    scale_y_discrete(limits = rev)
    

    enter image description here