Search code examples
rggplot2scaleaxisfacet

How to change the facet scales using ggplot2?


I'm trying to change the scale of some panels to get a better view. In facet_grid the scales are already "free", however, I need a different scale for the row corresponding to the First Range. Does anyone know how to do this?

library (ggplot2)

Source <- c(rep("Water", 12), rep("Oil", 12))
Range <- rep((c(rep("First", 4), rep("Second", 8))),2)
Xaxis <- c(0,1,2,5,0,1,2,5,10,20,30,40,
           0,1,2,5,0,1,2,5,10,20,30,40)
Yaxis <- c(0,1,2,5,0,1,2,5,10,20,30,40,
           0,1,2,5,0,1,2,5,10,20,30,40)

DF <- data.frame(Source, Range, Xaxis, Yaxis)

ggplot(data = DF, aes(x = Xaxis, y = Yaxis)) +
  geom_smooth(method = "lm") +
  geom_point() +
  facet_grid(Range~Source,
             scales = "free")

enter image description here

I would like the front row to look like this:

enter image description here


Solution

  • An alternative is to use facet_wrap() instead of facet_grid(), e.g.

    library(tidyverse)
    
    Source <- c(rep("Water", 12), rep("Oil", 12))
    Range <- rep((c(rep("First", 4), rep("Second", 8))),2)
    Xaxis <- c(0,1,2,5,0,1,2,5,10,20,30,40,
               0,1,2,5,0,1,2,5,10,20,30,40)
    Yaxis <- c(0,1,2,5,0,1,2,5,10,20,30,40,
               0,1,2,5,0,1,2,5,10,20,30,40)
    
    DF <- data.frame(Source, Range, Xaxis, Yaxis)
    
    ggplot(data = DF, aes(x = Xaxis, y = Yaxis)) +
      geom_smooth(method = "lm") +
      geom_point() +
      facet_wrap(Range~Source,
                 scales = "free")
    

    example_1.png