Sorting factors in multipanel plot in ggplot2 according to the first panel

烈酒焚心 提交于 2019-12-06 12:07:47

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)

giving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!