是否可以根据第一个面板对ggplot2
中的多面板图中的因子进行排序?第一个面板决定订单,其余面板遵循该订单。
以下是一个例子:
require(ggplot2)
set.seed(36)
xx<-data.frame(YEAR=rep(c("X","Y"), each=20),
CLONE=rep(c("A","B","C","D","E"), each=4, 2),
TREAT=rep(c("T1","T2","T3","C"), 10),
VALUE=sample(c(1:10), 40, replace=T))
ggplot(xx, aes(x=CLONE, y=VALUE, fill=YEAR)) +
geom_bar(stat="identity", position="dodge") +
facet_wrap(~TREAT)
这给了我这个情节:
现在,我想根据CLONE
中的VALUE
按降序排列YEAR X
(从最高到最低),但仅限于控制(C
面板) 。然后应该为T1
,T2
和T3
维护此订单。通过查看上面的图表,我希望小组C
排序为CLONE C
,B
或D
(均为5),A
和{{1} }。然后应该为剩余的面板复制此E
的顺序。
答案 0 :(得分:1)
在ggplot中没有简单的方法可以做到这一点,因为你必须重新排序CLONE
3个条件,TREAT,YEAR和VALUE,否则forcats::fct_reorder2
可能是一个选项。
相反,从对应于YEAR =“X”的数据子集中提取CLONE的顺序,
TREAT =“C”,并根据此子集重新定义整个数据集的因子水平。
library("ggplot2")
library("dplyr")
set.seed(36)
xx <- data.frame(YEAR = rep(c("X","Y"), each = 20),
CLONE = rep(c("A","B","C","D","E"), each = 4, 2),
TREAT = rep(c("T1","T2","T3","C"), 10),
VALUE = sample(c(1:10), 40, replace = TRUE), stringsAsFactors = FALSE)
clone_order <- xx %>% subset(TREAT == "C" & YEAR == "X") %>%
arrange(-VALUE) %>% select(CLONE) %>% unlist()
xx <- xx %>% mutate(CLONE = factor(CLONE, levels = clone_order))
ggplot(xx, aes(x = CLONE, y = VALUE, fill = YEAR)) +
geom_bar(stat = "identity", position = "dodge") +
facet_wrap(~TREAT)
给