我想以更好的方式重新安排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=''))
结果如下:
有没有办法根据频率重新排列情节?一些lab
频率(或每种类型的点数)非常低(1-3
)。我想安排他们的频率而不是他们的标签订单的情节facet_wrap
。一个优点是减少绘图区域并从图中获得更好的直觉。
可以使用动态计算的频率值并将它们传递给facet_wrap
来完成吗?或者它应该使用dplyr
方法单独完成,并将数据分成低/中/高频率的图集?
答案 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=''))
如果您想要反转因子级别,请在使用.desc = TRUE
时设置fct_reorder
。