根据子图

时间:2017-10-10 19:23:03

标签: r ggplot2 dplyr facet-wrap

我想以更好的方式重新安排facet_wrap地块。

library(ggplot2)

set.seed(123)
freq <- sample(1:10, 20, replace = T)
labels <- sample(LETTERS, 20)
value <- paste("i",1:13,sep='')

lab <- rep(unlist(lapply(1:length(freq), function(x) rep(labels[x],freq[x]))),2)
ival <- rep(unlist(lapply(1:length(freq), function(x) value[1:freq[x]])),2)

df <- data.frame(lab, ival, type=c(rep('Type1',119),rep('Type2',119)),val=runif(238,0,1))


ggplot(df, aes(x=ival, y=val, col = type, group = type)) + 
    geom_line() + 
    geom_point(aes(x=ival, y=val)) +
    facet_wrap( ~lab, ncol=3) + 
    theme(axis.text.x=element_text(angle=45, vjust=0.3)) + 
    scale_x_discrete(limits=paste('i',1:13,sep=''))

结果如下:

enter image description here

有没有办法根据频率重新排列情节?一些lab频率(或每种类型的点数)非常低(1-3)。我想安排他们的频率而不是他们的标签订单的情节facet_wrap。一个优点是减少绘图区域并从图中获得更好的直觉。

可以使用动态计算的频率值并将它们传递给facet_wrap来完成吗?或者它应该使用dplyr方法单独完成,并将数据分成低/中/高频率的图集?

1 个答案:

答案 0 :(得分:2)

这是一个想法。我们可以使用dplyr计算lab中每个组的数量,并使用fct_reorder中的forcats来重新排序因子级别。

library(dplyr)
library(forcats)

df2 <- df %>%
  group_by(lab) %>%
  mutate(N = n()) %>%
  ungroup() %>%
  mutate(lab = fct_reorder(lab, N))

ggplot(df2, aes(x=ival, y=val, col = type, group = type)) + 
  geom_line() + 
  geom_point(aes(x=ival, y=val)) +
  facet_wrap( ~lab, ncol=3) + 
  theme(axis.text.x=element_text(angle=45, vjust=0.3)) + 
  scale_x_discrete(limits=paste('i',1:13,sep=''))

enter image description here

如果您想要反转因子级别,请在使用.desc = TRUE时设置fct_reorder