Search code examples
rggplot2boxplotfacet-wrap

ggplot box plot faceting


I am using the following code to make a ggplot box plot:

     p <- ggplot(data = five, mapping = aes(x = variable, y = value, fill = variable)) +
      geom_boxplot(alpha = .3) + 
      geom_jitter(alpha = .3) + 
      labs(title = "Stock Data", x = "Index", y = "Percent Return") + 
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5)) +
      facet_wrap(vars(variable))
     p 

Plot

Is there any way to remove the white space from the unused x-axis variables? I realize that I can make three separate charts and then arrange them side by side but was curious if it could be done on the same chart?


Solution

  • scales = "free" needed to be added to the facet_wrap argument.

    p <- ggplot(data = five, mapping = aes(x = variable, y = value, fill = variable)) +
          geom_boxplot(alpha = .3) + 
          geom_jitter(alpha = .3) + 
          labs(title = "Stock Data", x = "Index", y = "Percent Return") + 
          theme_bw() +
          theme(plot.title = element_text(hjust = 0.5)) +
          facet_wrap(vars(variable), scales = "free")
        
        p 
    

    enter image description here