Pete900
Pete900

Reputation: 2176

Fill ggplot facet panel with white space in loop

There are lots of questions on how to arrange ggplots in a grid using loops. However, I can't piece together what I'm after.

I want to plot an arbitrary number of equally sized graphs in a loop. Crucially, I want to use facet_wrap AND pre split the data into groups (explained why below). Here is an example:

df <- mtcars
df$car <- rownames(df)

ucar <- unique(df$car)

# Split data into groups of n (6's here)
split6s <- split(ucar, ceiling(seq_along(ucar)/6))

p <- list()

# For each group of 6, plot something (mpg vs wt) faceted by group (car)
for(i in 1 :length(split6s)){
  # Subset for group
  temp <- subset(df, car %in% split6s[[i]])    

    # Save plot forcing facet with 1 row
    p[[i]] <- ggplot(temp, aes(mpg, wt)) + geom_point() + 
                facet_wrap(~car, nrow = 1)
}

p[[5]]

enter image description here

p[[6]]

enter image description here

Desired p[[6]]

enter image description here

I want to do this so that I can standardize the size of some graphs in rmarkdown but use facets instead of just grobbing individual plots together.

Upvotes: 1

Views: 478

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24262

I am not sure if this is the solution that you are looking for.

library(ggplot2)
library(grid)

df <- mtcars
df$car <- rownames(df)
ucar <- unique(df$car)
split6s <- split(ucar, ceiling(seq_along(ucar)/6))

p <- list()
for(i in 1 :length(split6s)){
  temp <- subset(df, car %in% split6s[[i]])    
  p[[i]] <- ggplot(temp, aes(mpg, wt)) + geom_point() + 
                facet_wrap(~car, nrow = 1)
}

g5 <- ggplotGrob(p[[5]])
g6 <- ggplotGrob(p[[6]])

# Delete left panels     
for (k in c(4:7, 16:19, 34:37)) {
  g5$grobs[[k]] <- nullGrob()
}
# Copy Maserati and Volvo panels
g5$grobs[[2]] <-  g6$grobs[[2]]
g5$grobs[[3]] <-  g6$grobs[[3]]
g5$grobs[[14]] <-  g6$grobs[[6]]
g5$grobs[[15]] <-  g6$grobs[[7]]
g5$grobs[[32]] <-  g6$grobs[[12]]
g5$grobs[[33]] <-  g6$grobs[[13]]
# Move left x-axis label
g5$grobs[[39]]$children[[1]]$x <- unit(1/6, "npc")

grid.draw(g5)

enter image description here

Upvotes: 1

Related Questions