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()
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?