Home > database >  extract individual panels of facet plot to re-arrange
extract individual panels of facet plot to re-arrange

Time:08-02

I would like to rearrange a facet plot with 3 panels to have them fit better in a poster presentation. Currently, I have A over B over C (one column), and it is important to keep B over C.

What I would like is to have a square (2x2) presentation, with A over nothing, and B over C.

Can I either extract the individual panels of the plot, or create a facet with no axes or other graphic (like plotgrid with a NULL panel).

CodePudding user response:

A second option would be the ggh4x package which via facet_manual adds some flexibility to place the panels:

library(ggplot2)
library(ggh4x)

design <- "
AB
#C"

ggplot(mtcars, aes(mpg, disp))  
  geom_point()  
  facet_manual(~cyl, design = design)

CodePudding user response:

One approach could be creating separate plots using nest() and map() from {tidyverse} and then using {patchwork} package to align them as we want.

(Since OP didn't provide any data and code, I am using builtin mtcars dataset to show how to do this). Suppose This is the case where we have a facetted plot with 3 panels in a 3 x 1 format.

library(tidyverse)

# 3 x 1 faceted plot
mtcars %>% 
  ggplot(aes(mpg, disp))  
  geom_point()  
  facet_wrap(~cyl, nrow = 3)

3 x 1 facet plot

Now to match the question, lets suppose panel for cyl 4 is plot A, panel for cyl 6 is plot B and for cyl 8 is plot C.

So to this, we first created a nested dataset with respect to facet variable using group_by(facet_var) %>% nest() and then map the ggplot over the nested data to get plots (gg object) for each nested data.

library(tidyverse)
library(patchwork)


# Say, plotA is cyl 4
# plotB is cyl 6
# plotC is cyl 8

# 2 x 2 facet plot
plot_data <- mtcars %>% 
  group_by(cyl) %>% 
  nest() %>% 
  mutate(
    plots = map2(
      .x = data,
      .y = cyl,
      .f = ~ ggplot(data = .x, mapping = aes(mpg, disp))  
        geom_point()  
        ggtitle(paste0("cyl is ",.y))
    )
  )

plot_data
#> # A tibble: 3 × 3
#> # Groups:   cyl [3]
#>     cyl data               plots 
#>   <dbl> <list>             <list>
#> 1     6 <tibble [7 × 10]>  <gg>  
#> 2     4 <tibble [11 × 10]> <gg>  
#> 3     8 <tibble [14 × 10]> <gg>

Then simply align the plots using {patchwork} syntax as we wanted. I have used plot_spacer() to create blank space.

plot_data
plots <- plot_data$plots

plots[[2]]    plots[[1]]   plot_spacer()   plots[[3]]  
  plot_annotation(
    title = "A 2 X 2 faceted plot"
  )

2 x 2 plot

  • Related