在ggplot2中为每个构面指定自定义绘图顺序

时间:2017-05-28 01:56:58

标签: r ggplot2

当订单变量不在整个方面重复时,使用facet_wrap的地块排序正常工作,例如:

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

如果您尝试对排序类别在构面中复制因子项的数据重复此操作,则会出现错误:

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

如果我们不能使用因子,是否还有其他方法可以根据mtcars示例单独订购地块方面?

1 个答案:

答案 0 :(得分:1)

设置x的级别时会出现问题。 ggplot不知道如何处理具有相同名称的多个级别,因此该函数失败。如果您将其设置为levels = unique(x),则确实有效:

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