0

I have a data frame containing four variable: the outcome (y) and 3 other categorical factors (named x, z, and w). I wanted to create a bar plot using geom_bar() from ggplot2 in such a way that the x-axis is x (6 levels), with z as a grouping/colour factor (aes(x=x, y=y, fill=z)). In addition, I want to show the bars in different panels for the two levels of w using facet_wrap(~w). However, when I try to order the bars based on the magnitude of y (descending order) using various tricks discussed on internet (e.g. aes(x=reorder(x, -y), y=y, fill=z)) the results were not satisfying (not ordered).

So, can someone please help me solve my issue? See below an example data and the code.

Thanks in advance.

library(ggplot2)
df <- data.frame(y=rpois(72, 10), 
                 x=rep(letters[1:6], each=6),
                 z=rep(1:2, each=3),
                 w=rep(LETTERS[1:2], each=36))

df$z <- as.factor(df$z)
df$w <- as.factor(df$w)

ggplot(df, aes(x=x, y=y,  fill=z))+
  geom_bar(stat = "identity", position = "dodge")+
  theme_bw()+
  facet_wrap(~w)+
  theme(legend.position = "top",
        legend.title = element_blank(),
        legend.direction = "horizontal",
        axis.text.x = element_text(angle = 45, hjust = 1))

```
markus
  • 25,843
  • 5
  • 39
  • 58
  • welcome to SO. If you are creating a random sample (`rpois`) please use set.seed(x) for reproducibility. Do you want to order the x-axis by group 1 or 2? – tjebo Aug 07 '19 at 22:36
  • 3
    Is this what you're looking for @Alemu https://stackoverflow.com/a/52214383/786542? – Tung Aug 07 '19 at 23:25
  • @Tjebo Thanks for the suggestion. I want to order the x-axis separately by the magnitude of y only maintaining the grouping colour for each bar. – Alemu Assefa Aug 08 '19 at 07:40
  • Each x contains two bars (z = 1 and z = 2) with different order of y values - ordering for which would results in different orders. You could either order by the total of both groups or decide to order for one of z - or you add z as another facetting variable. – tjebo Aug 08 '19 at 10:33

0 Answers0