1

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?

hpesoj626
  • 3,529
  • 1
  • 17
  • 25

1 Answers1

2

If you expect the bars to be increasing within each facet, the same value of y needs to be in a different position for different facets. Try this instead:

dat3 <- dat %>%
  mutate(x.y = paste(x, y, sep = ".")) %>%
  mutate(x.y = factor(x.y, levels = x.y[order(z)]))
# this creates a new variable that combines x & y; different facets
# simply use different subsets of values from this variable

ggplot(dat3, aes(x.y,z)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "y", breaks = dat3$x.y, labels = dat3$y) +
  facet_wrap(~x, scales = "free")

plot

Z.Lin
  • 28,055
  • 6
  • 54
  • 94