Search code examples
rggplot2data-visualizationfacet-wrap

Changing facet labels in face_wrap() ggplot2


So the code below is working w/out errors, and I am trying to fix the following issue.

First, I am trying to change the group name for each graph to say, for instance, "< 1500 dollars" to refer to the group of workers earnings $1500 or less etc...

I tried this solution: to change the underlying factor level names but I keep getting this error:

"Error: unexpected ',' in ""< 1500 Dollars",""

outflows <- Wage_Outflows
levels(outflows$wage_group)
"< 1500",     "1501 ~ 2999", "3000", 
levels(outflows$wage_group) <- c("< 1500 Dollars", "1501 ~ 2999 Dollars", "3000 Dollars")
text.on.each.panel <-"Dollars"

p1 = ggplot(Wage_Outflows[Wage_Outflows$wage_group=="< 1500",], aes(x = year, y = labor)) +
       geom_point() +
       scale_y_continuous(breaks=seq(4000000, 6500000, by = 400000)) +
                             facet_wrap(~ wage_group) + theme(axis.title.x = element_blank())

p2 = ggplot(Wage_Outflows[Wage_Outflows$wage_group=="1501 ~ 2999",], aes(x = year, y = labor)) +
       geom_point() +
       scale_y_continuous(breaks=seq(800000, 1100000, by = 20000)) +
       facet_wrap(~ wage_group) + theme(axis.title.x = element_blank())


p3 = ggplot(Wage_Outflows[Wage_Outflows$wage_group=="3000",], aes(x = year, y = labor)) +
       geom_point() +
       scale_y_continuous(breaks=seq(50000, 120000, by = 5000)) +
       facet_wrap(~ wage_group) + theme(axis.title.x = element_blank())


grid.arrange(p1, p2,p3, ncol=1)

enter image description here


Solution

  • For your first question have a look at the labeller argument in the facet_wrap function.

    And for your second question the labs function might be the solution.

    p1 = ggplot(Wage_Outflows[Wage_Outflows$wage_group=="< 1500",], 
         aes(x = year, y = labor)) +
         geom_point() +
         scale_y_continuous(breaks=seq(4000000, 6500000, by = 400000)) +
         labs(y = "Number of workers") +
         facet_wrap(~ wage_group, labeller = labeller(wage_group = c(`< 1500` = "< 1500 
         dollars"))) +
         theme(axis.title.x = element_blank())
    
    

    Maybe you can shorten your code like this:

    # Example dataset: 
    
    df <- data.frame(wage_group = rep(c("A","B","C"), each = 10),
                     year = 2001:2010,
                     labor = seq(5000,34000, 1000))
    
    
    ggplot(df , aes(x = factor(year), y = labor)) +
      geom_point() +
      labs(y = "# of workers") +
      facet_wrap(~wage_group, ncol = 1, scales = "free",
                 labeller = labeller(wage_group = c(`A` = "less than 1500 dollars", 
                 `B` = "1500-2999 dollars", `C` = "more than 3000 dollars"))) +
      theme(axis.title.x = element_blank())