'How to set individual x-axis when there is multiple variables in cols with facet_grid_sc

I am trying to customize the scales for each x-axis, but I always get the error below:

Error in .subset2(x, i, exact = exact) : subscript out of bounds

Below is script I am trying to create. Customize the x-axis is needed, because its values are crowded.

library(dplyr)
library(ggplot2)
library(facetscales)

country=factor(c(rep("Japan", 3), rep("US",4), rep("Europe", 7),rep("US",3), "Europe", rep("Japan", 3), rep("US",4), rep("Europe", 3), "US", rep("Europe", 3)))
mtcarros <- mtcars %>% 
  mutate(country=country)

# How should I create the individual scales for the x-axis
scales_x <- list()

ggplot(mtcarros, aes(mpg, cyl))+
  geom_point()+
  facet_grid_sc(gear~carb+country, scales = list(x=scales_x))

So my questions is: How to create the individual scales for the x-axis?



Solution 1:[1]

The specific error you report is occurring because you have two variables on the right hand side of your faceting formula - this isn't possible, since it implies a 3-D array of facets rather than a 2-D array (carb would have to be "coming out of the screen"). It is possible to nest facets using other extension packages such as ggh4xto allow a third faceting dimension, but this seems tangential to your main question of how to use facet_grid_sc

To do this, you need to make a named list of scale objects, with one scale for each named level:

scales_x <- list(Japan = scale_x_continuous(label = ~paste(.x, "km/l")),
                 US = scale_x_continuous(label = ~paste(.x, "mpg")),
                 Europe = scale_x_continuous(label = ~paste(.x, "km/l")))

ggplot(mtcarros, aes(mpg, cyl))+
  geom_point()+
  facet_grid_sc(gear~country, scales = list(x=scales_x))

enter image description here

You can set breaks, etc individually for each factor level of each faceting variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1