Home > other >  How to flip order of bars in a grouped bar chart?
How to flip order of bars in a grouped bar chart?

Time:04-07

I am constructing a group bar chart. Here is the code I have written thus far:

p <- ggplot(data, aes(x = Word, y = Estimate, fill = Group))  
  geom_col(position = "dodge")  
  geom_errorbar(
    aes(ymin = Estimate - SE, ymax = Estimate   SE),
    position = position_dodge(.9),
    width = .2
  )   labs(x = "Focal Word", y = "Norm of Beta Coefficients", title = "Figure 1: Results of Context Embedding Regression Model", caption = "p.")

p   theme(axis.text.x  = element_text(angle = 90))

This yields the following plot:enter image description here

I am happy with this overall, but I want the order of the bars in the pairs to be flipped: pre-crisis should come before post-crisis. Does anyone know how to solve this problem? Any help would be appreciated. Here are data for a minimally reproducible example:

structure(list(Word = c("Economy", "Economy", "Civil Rights", 
"Civil Rights", "Health", "Health"), Group = c("Pre-Crisis", 
"Post-Crisis", "Pre-Crisis", "Post-Crisis", "Pre-Crisis", "Post-Crisis"
), Estimate = c(0.08197375, 0.07068641, 0.3041591, 0.4429921, 
0.09703231, 0.1558241), SE = c(0.006251288, 0.003762346, 0.04490241, 
0.06448664, 0.01176194, 0.01211825)), row.names = c(NA, 6L), class = "data.frame")

CodePudding user response:

One option would be to convert to use forcats::fct_rev which converts to factor and reverse the order of your Group column:

library(ggplot2)

p <- ggplot(data, aes(x = Word, y = Estimate, fill = forcats::fct_rev(Group)))  
  geom_col(position = "dodge")  
  geom_errorbar(
    aes(ymin = Estimate - SE, ymax = Estimate   SE),
    position = position_dodge(.9),
    width = .2
  )  
  labs(x = "Focal Word", y = "Norm of Beta Coefficients", title = "Figure 1: Results of Context Embedding Regression Model", caption = "p.")

p   theme(axis.text.x = element_text(angle = 90))

  • Related