Search code examples
rggplot2facet-wrapfacet-grid

How to change x-axis limits for specific facets in ggplot2 facet_grid?


I'm creating a facet_grid plot using ggplot2 in R.

Reproducible example below with the mtcars dataset.

I want to manually change the x-axis limits for the facets corresponding to 4-cylinder cars only. Here's my minimal reproducible example:

enter image description here

library(ggplot2)
library(dplyr)

mtcars <- mtcars %>%
  mutate(cyl = as.factor(cyl), 
         gear = as.factor(gear), 
         carb = as.factor(carb))

# Plot the empirical CDF with different lines for each carb type, and facet by cyl and gear
ggplot(mtcars, aes(x = mpg, color = carb, linetype = carb)) +
  stat_ecdf(geom = "step") +
  theme_minimal() +
  facet_grid(cyl ~ gear, scales = "free")

I want to set the x-axis limit to a maximum of say 25 for the facets where cyl is 4, while keeping the other facets' x-axis limits unchanged. How can I do this?

Any help would be greatly appreciated!


Solution

  • You can use ggh4x::facetted_pos_scales to set the scale individually per panel, i.e. for your desired result you can set the upper limit to 25 for the second column of the grid aka gear = 4 like so:

    mtcars <- mtcars |> 
      transform(
        cyl = as.factor(cyl),
        gear = as.factor(gear),
        carb = as.factor(carb)
      )
    
    library(ggplot2)
    library(ggh4x)
    
    ggplot(mtcars, aes(x = mpg, color = carb, linetype = carb)) +
      stat_ecdf(geom = "step") +
      theme_minimal() +
      facet_grid(cyl ~ gear, scales = "free") +
      ggh4x::facetted_pos_scales(
        x = list(
          gear == 4 ~ scale_x_continuous(
            limits = c(NA, 25)
          )
        )
      )