Arranging Multiple Plots

Authors

Jiratchaya Nuanpirom

Prasert Yodsawat

Khunanon Chanasongkram

Published

May 17, 2023

# Load packages
pacman::p_load(
  "tidyverse",
  "cowplot",
  "grid"
)

1 Example: Differential Gene Expression Analysis in pasilla data set

Our goal in this section is to combine the results from the previous section into one image. We will use PCA plot pca_dds, DEG heat map hm_deg, and volcano plot p_volcano. Your first step should be to ensure that all plot objects are available in your R environment. To make it easier to arrange in this chapter.

It is also important to make sure that all plots are gg objects. To do so, simply type class() followed by the plot object as follows.

# Check the class of the plots
class(pca_dds)
class(hm_deg)
class(p_volcano)

As we can see the hm_deg that is generated by pheatmap() function of ComplexHeatmap library is different from the other plots. In order to make it compatible with other ggplot objects, we need to modify it using grid.grabExpr() of the ‘grid’ library. The following functions allow you to create a “grob”, “gTree”, or “gList” object that is compatible with ggplot2.

grob_hm <- grid.grabExpr(draw(hm_deg))

# Check class of the plot object again
class(grob_hm)

All plots can now be arranged together.

  1. Let’s start by combining PCA and volcano plots.
p_volc_pca <- plot_grid(
  pca_dds + theme(legend.position = "none"), 
  p_volcano + theme(legend.position = "none"), 
  nrow = 2, labels = "AUTO")
  1. Combine legend of the PCA and volcano using get_legend().
legend_pca <- get_legend(pca_dds)
legend_volcano <- get_legend(p_volcano)
  1. Put the first two plots together with the legends
p_volc_pca_lgd <- plot_grid(p_volc_pca, 
                            legend_pca,
                            legend_volcano,
                            nrow = 3,
                            rel_heights = c(1, 0.05, 0.05))
  1. Then combine with heat map
p_all <- plot_grid(p_volc_pca_lgd,
                   grob_hm,
                   ncol = 2,
                   labels = c("", "C"),
                   rel_widths = c(0.5, 0.5)) +
  theme(panel.background = element_rect(fill = "white", color = NA))
  1. Save the plot
# Save as PDF
ggsave(filename = "DEG_plots_volc_pca_hm.pdf",
      plot = p_all,
      scale = 1,
      width = 10,
      height = 10,
      units = "in",
      dpi = 400)

# save as PNG
ggsave(filename = "DEG_plots_volc_pca_hm.png",
      plot = p_all,
      scale = 1,
      width = 10,
      height = 10,
      units = "in",
      dpi = 400)

## Practice