Sorting factors in multichannel graphics in ggplot2 according to the first panel

Is it possible to sort factors in a multi-channel graph in ggplot2 according to the first panel? The first panel decides the order, and the remaining panels follow this order.

Here is an example:

 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) 

What gives me this plot:

enter image description here

Now I would like to sort CLONE based on VALUE in YEAR X in descending order (highest to lowest), but only for the control panel ( C ). Then this order should be maintained for T1 , T2 and T3 . If you look at the chart above, I want panel C sorted as CLONE C , B or D (both are 5), A and E Then this CLONE order should be replicated for the rest of the panels.

+2
source share
1 answer

There is no easy way to do this directly in ggplot, since you need to reorder CLONE 3, TREAT, YEAR and VALUE, otherwise forcats::fct_reorder2 could be an option. Instead, extract the CLONE order from the subset of data corresponding to YEAR = "X", TREAT = "C" and redefine the factor levels for the entire data set based on that 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) 

gives

Barchart of CLONE sorted by sub-panel

+1
source

All Articles