【问题标题】:Sorting factors in multipanel plot in ggplot2 according to the first panel根据第一个面板在 ggplot2 中的多面板图中排序因子
【发布时间】:2016-09-23 19:40:18
【问题描述】:

是否可以根据第一个面板在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)

这给了我这个情节:

现在我想根据YEAR X 中的VALUE 按降序(从高到低)对CLONE 进行排序,但仅限于控制(C 面板)。然后应为T1T2T3 维护此顺序。通过查看上面的图,我希望面板C 排序为CLONE CBD(均为5)、AE。然后应该为其余面板复制此CLONE 顺序。

【问题讨论】:

  • 您应该/可以将克隆变量定义为有序因子,您可以在其中根据 C 中的排序定义顺序。如果我是正确的,ggplot 将保持此顺序。

标签: r sorting ggplot2 facet


【解决方案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)

给予

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 2012-06-06
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 2019-01-29
    相关资源
    最近更新 更多