Skip to content
Snippets Groups Projects
combine_cluster_plots_and_save.R 2.04 KiB
#' Plot list of three plots in three columns and save to 'path' with filename
#' 'Cluster_overview_'cluster'.pdf'
#'
#' This function combines a list of three plots into a single plot with three columns
#' and saves it as a PDF file with a specified filename. The cluster number is
#' included as a title on the top of the plot.
#'
#' @param plot_list A list of three plots to combine.
#' @param cluster The cluster number to include in the plot title.
#' @param out_path The path where the plot should be saved. Default is 'path'.
#' @param w The width of the plot. Default is 'cm_width'.
#' @param h The height of the plot. Default is 'cm_height'.
#' @return combined plot
#' @import ggplot2
#' @importFrom cowplot get_legend plot_grid ggdraw draw_label
#' @export
combine_cluster_plots_and_save <- function(plot_list, cluster, out_path = path,
                                           w = cm_width, h = cm_height) {
  dir.create(out_path, showWarnings = FALSE)
  combo_pl <- cowplot::plot_grid(plot_list[[1]] + theme(legend.position = "none"),
                                 plot_list[[2]] + theme(legend.position = "none"),
                                 plot_list[[3]] + theme(legend.position = "none"),
                                ncol = 3, align = "h")
  legend <- cowplot::get_legend(plot_list[[3]] +
    #                             guides(fill = guide_legend(nrow = 1)) +
                                  theme(legend.position = "bottom"))
  title <- ggdraw() +
    draw_label(
      paste("Cluster:", cluster),
      fontface = 'bold',
      x = 0,
      hjust = 0
    ) +
    theme(
      # add margin on the left of the drawing canvas,
      # so title is aligned with left edge of first plot
      plot.margin = margin(0, 0, 0, 7)
    )
  combo_pl_with_legend <- cowplot::plot_grid(title, combo_pl, legend,
                                             ncol = 1, rel_heights = c(.1, 1, .1))
  ggsave(file.path(out_path, paste0("Cluster_overview_", cluster, ".pdf")),
         combo_pl_with_legend, width = w, height = h, units = "cm")
  return(combo_pl_with_legend)
}