Home > front end >  Is there a way to add facet.grid-type strip labels to regular plots so that plots aggregated in grid
Is there a way to add facet.grid-type strip labels to regular plots so that plots aggregated in grid

Time:03-25

It's my understanding that one of the big drawbacks of facet_grid is that you cannot specify the axis limits of groups of panels. Thus, I created four graphs, I added the axis limits I wanted and manually added them together using grid.arrange in the gridExtra package. However, I'd like if these plots match with the other ones I've created using face_grid. I think the bar labels that are auto-generated in facet_grid are controlled in theme() under the strip. related functions but I have no idea how to go about "recreating" these strip labels for my individual plots. Anyone know?

Here's the graph I've created with grid.arrange() enter image description here

And here's the graph I've created with facet.grid()

enter image description here

I'd like the gray shaded labels from facet.grid() in my grid.arrange() generated plot.

Thanks!

CodePudding user response:

Well, a simple approach would be to facet each of your four subplots by adding facet_grid. Doing so will automatically add strip text boxes to each of the subplots. In my code below I make use of a custom function and set the specs of each facet_grid conditionally using an if-else.

Using some fake example data and making use of patchwork instead of grid.arrange:

df <- data.frame(
  row = c("K", "r"),
  col = rep(c("Female", "Male"), each = 2),
  x = rep(1:2, each = 4),
  y = rep(1:2, each = 4)
)

# Split by facet row and col
df_split <- split(df, ~row   col)
# Order
df_split <- df_split[c("K.Female", "K.Male", "r.Female", "r.Male")]

plot_fun <- function(x, y) {
  facet_layer <- if (grepl("Female$", y) && !grepl("^r", y)) 
    facet_grid(.~col) 
  else if (grepl("Male$", y) && !grepl("^r", y)) 
    facet_grid(row~col)
  else if (grepl("Male$", y) && grepl("^r", y)) 
    facet_grid(row~.)
  
  ggplot(x, aes(x, y))  
    geom_point()  
    facet_layer
}

library(purrr)
library(ggplot2)
library(patchwork)

purrr::imap(df_split, plot_fun) %>% 
  wrap_plots() 

  • Related