user3022875
user3022875

Reputation: 9018

ordering y axis with facet

I have this data frame

library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat %>% arrange(parent,-count )

 parent group value count
1      F  D(5)     4     5
2      F  A(4)     3     4
3      J  A(4)     1     4
4      J  C(3)     2     3

You can see above that the data is ordered by parent and then count descending. I would like the chart to keep this ordering BUT when I plot it in the "J" chart C(3) comes on top of A(4) and that should be revered. How can that be done?

ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")

Upvotes: 1

Views: 447

Answers (2)

Roman
Roman

Reputation: 17678

You can try:

dat %>% arrange(parent,-count ) %>% 
  mutate(group2=factor(c(2,1,4,3))) %>% 
  ggplot(aes(x = group2, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")+
  scale_x_discrete(breaks=1:4,labels = c("A(4)","D(5)","C(3)","A(4)"))

Upvotes: 0

Eric Watt
Eric Watt

Reputation: 3250

You can set your factor on the group column using the currently ordered values as the levels (reversed to get the ordering you want). This will lock in the ordering.

library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat <- dat %>% arrange(parent,-count )

dat$group <- factor(dat$group, levels = rev(unique(dat$group)))

ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")

Upvotes: 2

Related Questions