Search code examples
rggplot2facet

Reorder X variable based on Facet variable


I'm creating a facet grid. I'm attempting to reverse the order of levels on the x-axis (Context) based on the level of the specified facet variable(.~Order).

(E.g., For Order, if "NFF", then order of Context = "NF", "IF"; if "IFF", then order of Context = "IF", "NF").

Edit Data I'm working with:

Order <- c("NFF", "NFF", "NFF", "NFF", "IFF", "IFF", "IFF", "IFF")
Concept <- c("BT","BT", "H", "H", "BT", "BT", "H", "H")
Context <- c("NF", "IF", "NF", "IF", "IF", "NF", "IF", "NF")
Mean <- c(3.587, 3.857, 3.467, 3.101, 2.986, 3.965, 3.154, 3.555)
SE <- c(0.13, 0.229, 0.143, 0.251, 0.281, 0.159, 0.251, 0.143)

FlowExp1 <- data.frame(Order, Concept, Context, Mean, SE)

What I've attempted so far:

FlowExp1$Context <- factor(FlowExp1.3$Context,
                   levels = c("No Friction", "Implied Friction"))

limits <- aes(ymax = Mean + SE, ymin=Mean - SE)
dodge <- position_dodge(width=0.5)
cb<- c("dark grey", "grey30")

p <- ggplot(FlowExp1, aes(fill=Concept, y=Mean, x=Context))
p2<- p + geom_bar(position="dodge", stat="identity", width = .5)


p2 + 
  geom_bar(position=dodge) + 
  scale_fill_manual(values=cb, guide = FALSE)+
  geom_errorbar(limits, position=dodge, width=0.25) + 
  ylim(0,5) +
  facet_grid(. ~ Order)

This almost works, I just need to reverse the order of Context on the second graph of the facet_grid.


Solution

  • You could do this by creating a dummy variable that is the interaction between the variable on the x-axis and the variable you are faceting by,

    library(ggplot2)
    
    ## Use a subset of the diamonds dataset
    data(diamonds)
    dat <- droplevels(with(diamonds, diamonds[color %in% c("E","I") & 
                                     clarity %in% c("SI2", "SI1"), ]))
    
    ## See what it looks like first
    p <- ggplot(dat, aes(fill=color, y=carat, x=clarity))
    p2 <- p + geom_bar(position="dodge", stat="identity", width=0.5)
    p2 + facet_grid(. ~ cut, scales="free_x")
    

    enter image description here

    The goal here is to change the order of clarity (x-axis) in this figure only in the "Premium" facet.

    ## Create a new factor of the interactions between variables of interest
    dat$fact <- with(dat, interaction(cut, clarity))
    
    ## Change the order of clarity in "Premium" facet only
    inds <- levels(dat$fact)
    inds[grep("Premium", inds)] <- rev(grep("Premium", inds, value=T))
    dat$fact <- factor(dat$fact, levels=inds)
    
    ## Plot it
    p <- ggplot(dat, aes(fill=color, y=carat, x=fact))
    p2 <- p + geom_bar(position="dodge", stat="identity", width=0.5)
    p2 + facet_grid(. ~ cut, scales="free_x") +
      scale_x_discrete(labels="") + xlab("Clarity")
    

    enter image description here

    Notice the order of SI2 and SI1 has switched in the Premium panel.