Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")

>Solution :

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))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading