Search code examples
rggplot2plotfacet-grid

ggplot2, facet grid with free scales and spaces


I hadn't plotted much with R so far, I want to facet the plot with free scales and spaces. What I tried so far is

ggplot(df3, aes(x = Scores, y = Value)) +
  geom_bar( aes(fill=Input),
            stat = "identity", position = position_dodge()
  ) + scale_fill_manual(values = c("#EFC000FF","#868686FF", "#0073C2FF", "#CD534CFF"))+ theme_pubr() +
facet_grid(. ~ Group, scales = "free", space = "free_x") 

enter image description here

So I cant get the free y scales. This is probably trivial, but I didn't find anything that compares.


Solution

  • You cannot get free "y" scales by facet_grid() for each row, but if you insisted on it, you could try using facet_grid2() from {ggh4x} package.

    For example:

    # install.packages("ggh4x")
    ggplot(df3, aes(x = Scores, y = Value)) +
      geom_bar( aes(fill=Input),
                stat = "identity", position = position_dodge()
      ) + 
      scale_fill_manual(values = c("#EFC000FF","#868686FF", "#0073C2FF", "#CD534CFF")) + 
      theme_pubr() +
      ggh4x::facet_grid2(. ~ Group, independent = "y", scales = "free", space = "free_x") 
    

    See this manual for more information.