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))
```