根据第一个面板在ggplot2中的多面板图中的排序因子
是否可以根据第一个面板在ggplot2
中的多面板图中对因子进行排序?第一个面板确定顺序,其余面板遵循该顺序.
Is it possible to sort factors in a multipanel plot in ggplot2
according to the first panel? The first panel decides the order and the remaining panels follow that order.
这里是一个例子:
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)
哪个给我这个情节:
现在,我想基于YEAR X
中的VALUE
以降序(从最高到最低)对CLONE
进行排序,但仅针对控件(C
面板).然后应为T1
,T2
和T3
保持此顺序.通过查看上面的图,我希望将面板C
排序为CLONE C
,B
或D
(均为5),A
和E
.然后应将CLONE
的顺序复制到其余面板.
Now I would like to sort CLONE
based on the VALUE
in YEAR X
in a descending order (highest to lowest) but only for the Control (C
panel). This order should then be maintained for T1
, T2
, and T3
. By looking at the plot above, I want panel C
sorted as CLONE C
, B
or D
(both are 5), A
and E
. This order of CLONE
should then be replicated for the remaining panels.
在ggplot中没有简单的方法来正确执行此操作,因为您必须通过以下方式对CLONE重新排序
3个条件,即TREAT,YEAR和VALUE,否则可以选择forcats::fct_reorder2
.
而是从与YEAR ="X"相对应的数据子集中提取CLONE的顺序,
TREAT ="C",然后根据此子集为整个数据集重新定义因子水平.
There's no easy way to do this right in ggplot since you have to reorder CLONE by
3 conditions, TREAT, YEAR and VALUE, otherwise forcats::fct_reorder2
could have been an option.
Instead, extract the order of CLONE from the subset of data corresponding to YEAR = "X",
TREAT = "C", and re-define your factor levels for the whole data set based on this subset.
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)
给予