I want to arrange the bar graphs in ascending order by the levels of a variable. The other posts here and here do not work.
Here is an example data
x <- c(rep(letters[1:2], each = 6))
y <- c(rep(letters[3:8], times = 2))
z <- c(2, 4, 7, 5, 11, 8, 9, 2, 3, 4, 10, 11)
dat <- data.frame(x,y,z)
What I want to achieve is to plot a bar graph of the levels of y
grouped by x
in increasing order.
The following arranges y
in increasing order.
library(tidyverse)
dat2 <- dat %>% group_by(y) %>%
arrange(x, z) %>%
ungroup() %>%
mutate(y = reorder(y, z))
dat2
However, the resulting plots are not what I was expecting.
ggplot(dat2, aes(y,z)) +
geom_bar(stat = "identity") +
facet_wrap(~x, scales = "free")
How can I arrange the levels of y
in increasing order of z
by x
?