-1

Plot ordering with facet_wrap works ok when the order variables are not duplicated across the facets, e.g:

mtcars %>% arrange(mpg) %>% 
  mutate(car = row.names(mtcars), car = factor(car, levels = car)) %>% 
  ggplot(aes(car, mpg)) + geom_bar(stat='identity') +
  facet_wrap(~ cyl, scales='free') + coord_flip()

enter image description here

When you try to repeat this for data where the ordering category duplicates factor items across the facets you get an error:

data.frame(x = c('a','b','c','a','b','c'), 
            y = c(4,2,1,3,5,7), grp = rep(c('A','B'), each=3)) %>% 
   arrange(-y) %>% mutate(x = factor(x, levels = x)) %>% 
   ggplot(aes(x, y)) + geom_bar(stat='identity') +
   facet_wrap(~ grp, scales='free') + coord_flip()
Warning messages:
1: In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated
2: In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated
3: In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated
4: In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated

If we can't use factors is there any other way to order the plot facets individually in line with the mtcars example?

mt1022
  • 16,834
  • 5
  • 48
  • 71
geotheory
  • 22,624
  • 29
  • 119
  • 196

1 Answers1

1

The problem happens when you set the levels of x. ggplot doesn't know how to deal with multiple levels with the same name, so the function fails. If you set that to levels = unique(x) it does work:

library(tidyverse)
data.frame(x = c('a','b','c','a','b','c'), 
           y = c(4,2,1,3,5,7), grp = rep(c('A','B'), each=3)) %>% 
    arrange(-y) %>% mutate(x = factor(x, levels = unique(x))) %>% 
    ggplot(aes(x, y)) + geom_bar(stat='identity') +
    facet_wrap(~ grp, scales='free') + coord_flip()

enter image description here

Sraffa
  • 1,658
  • 12
  • 27
  • Sorry @Sraffa this isn't quite what I'm after - I need both facets to order downwards from biggest to smallest.. – geotheory May 28 '17 at 11:00
  • I see. I added a flag for the question being a duplicate, I think the link will help. – Sraffa May 28 '17 at 13:45