Home > Software design >  The parameter scale does not work in ggplot2 in r
The parameter scale does not work in ggplot2 in r

Time:07-13

I am using facet_grid() to draw multiple plots.

I set scales = 'free', but it didn't work for facet_1 = 'A', facet_2 = 'a' and facet_1 = 'b', facet_2 = 'B' (Top left and bottom right figures).

The x-axis range is too big for the two plot.

df = data.frame(
  x = c(0, 1, 0, 1, 0, 60, 0, 60),
  y = c(1.5, 0.3, 1.5, 0.3, 1.8, 0.1, 1.8, 0.1),
  facet_1 = c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
  facet_2 = c('a', 'a', 'b', 'b', 'b', 'b', 'a', 'a'))


df %>% 
  ggplot(aes(x = x, y = y))  
  geom_point()  
  geom_line()  
  facet_grid(facet_1~facet_2, scales = 'free', space = 'free') # scales = 'free_x' also doesn't work

enter image description here

Then, I have to use patchwork to replot.

df1 = df %>% filter(facet_1 == 'A',facet_2 == 'a') 
df2 = df %>% filter(facet_1 == 'A',facet_2 == 'b') 
df3 = df %>% filter(facet_1 == 'B',facet_2 == 'a') 
df4 = df %>% filter(facet_1 == 'B',facet_2 == 'b') 


p1 = df1 %>% ggplot(aes(x = x, y = y))   geom_point()   geom_line() 
p2 = df2 %>% ggplot(aes(x = x, y = y))   geom_point()   geom_line() 
p3 = df3 %>% ggplot(aes(x = x, y = y))   geom_point()   geom_line() 
p4 = df4 %>% ggplot(aes(x = x, y = y))   geom_point()   geom_line() 

library(patchwork)

p1 p2 p3 p4  

enter image description here

My question is that is there a method that can draw a plot like using patchwork in ggplot with facet_grid()?

CodePudding user response:

you should use facet_wrap:

df %>% 
  ggplot(aes(x = x, y = y))  
  geom_point()  
  geom_line()  
  facet_wrap(facet_1~facet_2, scales = 'free')

CodePudding user response:

One option to achieve your desired result would be to use the ggh4x package which offers some useful extensions to overcome some of the limitations of the default facet_xxx, e.g. using ggh4x::facet_grid2 you could do:

library(ggplot2)
library(ggh4x)

ggplot(df, aes(x = x, y = y))  
  geom_point()  
  geom_line()  
  facet_grid2(facet_1~facet_2, scales = "free", independent = "all")

  • Related