0

I am trying to reorganize the order of "facets" in facet_wrap. How do I do this when there are duplicates variable names?

I have tried using code like the following:

df$facet = factor(df$Case, levels = c("L", "B", "R", "BC"))

However, this doesn't seem to work in my case because I have two "High" and two "Low" in "maskalthalf", as shown here:

enter image description here

I have also tried re-ordering the values in the dataframe itself, but ggplot puts things back into alphabetical order.

This is a sketch of what I am aiming for:

enter image description here

This is what I currently have:

enter image description here

Current code for graph:

ggplot(groups, aes(x = message, y = mean, group = factor(maskalthalf), fill = maskalthalf)) + 
  geom_bar(stat = "identity", width = 0.5, fill = "003900") +
  geom_text(aes(label = round(mean, digits = 1), vjust = -2)) + 
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) + 
  labs(title = "Evaluations of Personal and General Convincingness") + 
  ylab("Rating") + 
  xlab("Personal evaluation or general evaluation") + 
  ylim(0, 8) + 
  facet_wrap(~maskalthalf)

Data:

dput(groups)
structure(list(maskalthalf = c("Low", "Low", "High", "High"), 
    message = c("General", "Personal", "General", "Personal"), 
    mean = c(4.69879518072289, 4.8433734939759, 4.79090909090909, 
    6.38181818181818), se = c(0.149182255019704, 0.180996951567937, 
    0.144452868727642, 0.104112130946133)), row.names = c(NA, 
-4L), groups = structure(list(maskalthalf = c("High", "Low"), 
    .rows = structure(list(3:4, 1:2), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))
melbez
  • 960
  • 1
  • 13
  • 36
  • If you do `groups$message <- factor(groups$message, c('Personal', 'General'))` and `groups$maskalthalf <- factor(groups$maskalthalf, c('Low', 'High'))` and run your code it seems to give you the order that you want. What exactly is not working? – Ronak Shah Feb 01 '21 at 03:10

1 Answers1

1

You can use fct_relevel, but ungroup the dataframe first.

library(forcats)
library(ggplot2)
library(dplyr)

groups %>% 
  ungroup() %>% 
  mutate(message = fct_relevel(message, "Personal", "General"),
         maskalthalf = fct_relevel(maskalthalf, "Low", "High")) %>% 
  ggplot(aes(x = message, y = mean)) + 
  geom_col(width = 0.5, fill = "003900") +
  geom_text(aes(label = round(mean, digits = 1), vjust = -2)) + 
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) + 
  labs(title = "Evaluations of Personal and General Convincingness",
       y = "Rating",
       x = "Personal evaluation or general evaluation") + 
  ylim(0, 8) +
  facet_wrap(~maskalthalf)

enter image description here

neilfws
  • 32,751
  • 5
  • 50
  • 63