R/exportVirusPlot.R

Defines functions ExportVirusPlot

Documented in ExportVirusPlot

#' @title Export Virusparies Plots
#'
#' @description ExportVirusPlot allows the user to export plots in different formats.
#'
#' @details Export plots generated by functions within the Virusparies package.
#'
#' @param file_name Name of the output file.
#' @param export_plotobj (optional): If TRUE, exports the plot object in rds format with the same name as specified in file_name (default: FALSE).
#' @param plot The plot to be exported.
#' @param device The device used for output.
#' Can be one of "eps", "ps", "tex", "pdf", "jpeg", "tiff", "png", "bmp", "svg", or "wmf" (windows only).
#' If NULL (default), the device is guessed based on the filename extension.
#' @param path The directory where the plot will be saved. Default is NULL (working directory).
#' @param scale A scaling factor (default: 1).
#' @param width The width of the output file.
#' @param height The height of the output file.
#' @param units The units of the width and height parameters.
#' Can be one of "in", "cm", "mm", or "px".
#' @param dpi The resolution of the output device in dots per inch (default: 300).
#' @param limitsize Whether to limit the size of the output file to the dimensions of the plot (default: TRUE).
#' @param ... Additional arguments passed to.
#' @param align Specifies alignment of plots in the grid: "none" (default), "hv" (both directions), "h" (horizontally), or "v" (vertically).
#' @param axis Specifies alignment of plots by margins: "none" (default), or any combo of left ("l"), right ("r"), top ("t"), or bottom ("b")(e.g., "tblr" or "rlbt").
#' @param nrow (optional): Number of rows in the plot grid (default: NULL).
#' @param ncol (optional): Number of columns in the plot grid (default: NULL).
#' @param rel_widths Numeric vector of relative column widths. Default is 1 (equal widths).
#' @param rel_heights Numeric vector of relative row heights. Default is 1 (equal heights).
#' @param labels List of labels for plots. Default is NULL (no labels).labels="auto" and labels="AUTO" auto-generate lower and upper-case labels.
#' @param label_size Numeric label size (default: 14).
#' @param label_fontfamily Font family for labels. Default is NULL (theme default).
#' @param label_fontface Font face for labels (default: "bold").
#' @param label_colour Color for labels. Default is NULL (theme default).
#' @param label_x Single value/vector of x positions for labels,relative to each subplot. Default is 0 (left).
#' @param label_y Single value/vector of y positions for labels, relative to each subplot. Default is 1 (top).
#' @param hjust Horizontal adjustment for labels (default: -0.5).
#' @param vjust Vertical adjustment for labels (default: 1.5).
#' @param scale_grid Single value/vector > 0. Enables you to scale the size of all or select plots.
#' @param greedy Margin adjustment during alignment (default: TRUE).
#' @param byrow Arrange plots by row (TRUE, default) or column (FALSE).
#'
#' @details
#' ExportVirusPlot exports plots in various formats supported by Virusparies.
#' Supported devices include "eps", "ps", "tex", "pdf", "jpeg", "tiff", "png", "bmp", "svg", or "wmf" (Windows only).
#' When 'device' is set to NULL, the file extension in `filename` is used to determine the device.
#'
#' Depending on the plot, the final image might be cropped or truncated.
#' We recommend experimenting with height, width, and resolution.
#'
#' In addition, users can generate a grid layout containing multiple plots when a list containing multiple plots is provided as input.
#' This will then be exported using the chosen device.
#'
#' The following arguments are only used for export with grid layout:
#' - `align`: Specifies how plots are aligned within the grid.
#' - `axis`: Controls alignment of plots by margins.
#' - `nrow`, `ncol`: Define the structure of the plot grid.
#' - `rel_widths`, `rel_heights`: Adjust relative column and row sizes.
#' - `labels`, `label_size`, `label_fontfamily`, `label_fontface`, `label_colour`, `label_x`, `label_y`, `hjust`, `vjust`: Customize plot labels.
#' - `scale_grid`: Enables you to scale the size of all or select plots.
#' - `greedy`: Determines margin adjustments during alignment.
#' - `byrow`: Specifies the arrangement of plots in the grid.
#'
#' `export_plotobj` = TRUE exports the plot in the specified format (e.g., PNG, PDF, etc.)
#' and also saves the plot object in .rds format with the same file name. This allows the user to
#' import the plot object into R using the `readRDS` function and modify the plot further as needed.
#'
#' @return a message indicating that export was successful.
#'
#' @author Sergej Ruff
#' @examples
#' path <- system.file("extdata", "virushunter.tsv", package = "Virusparies")
#' vh_file <- ImportVirusTable(path)
#'
#' # Basic plot
#' plot <- VhgIdentityScatterPlot(vh_file,cutoff = 1e-5)
#'
#' \donttest{
#'
#' # first export
#' ExportVirusPlot(plot=plot$plot,file_name="testplot.png",width=8,height=6,
#' units="in",path=tempdir())
#'
#' # second export with device argument
#' ExportVirusPlot(plot=plot$plot,file_name="testplot",width=8,height=6,
#' units="in",device = "png",path=tempdir())
#'
#' }
#'
#' ## example 2 for multiple plots in 1 pdf file.
#'
#' path2 <- system.file("extdata", "virusgatherer.tsv", package = "Virusparies")
#' vg_file <- ImportVirusTable(path2)
#'
#' # Generate 3 plots
#' violinplot <- VgConLenViolin(vg_file=vg_file,cut = 1e-5,log10_scale = TRUE,
#' legend_position = "none",title = "",xlabel = "",reorder_criteria = NULL,
#'                              theme_choice = "minimal")
#' srarun <- VhgRunsBarplot(file = vg_file,groupby = "ViralRefSeq_taxonomy",
#' legend_position = "none",title = "",xlabel = "",reorder_criteria = NULL,
#'                          theme_choice = "minimal")
#' boxplot <- VhgBoxplot(vg_file,x_column = "ViralRefSeq_taxonomy",y_column = "ViralRefSeq_ident",
#' legend_position = "bottom",title = "",xlabel = "",
#'                       reorder_criteria = NULL,theme_choice = "minimal")
#'
#' # add plots to a list
#' plot_list <- list(violinplot$plot,srarun$plot,boxplot$boxp)
#'
#' \donttest{
#'
#' ExportVirusPlot(plot=plot_list,file_name="grid_testplot.pdf",width=16,height=12,
#' units="in",nrow = 3,ncol = 1,path=tempdir())
#'
#' }
#'
#' @seealso
#' VirusHunterGatherer is available here: \url{https://github.com/lauberlab/VirusHunterGatherer}.
#'
#' @importFrom cowplot ggsave2 plot_grid
#' @importFrom tools file_path_sans_ext
#' @export
ExportVirusPlot <- function(
    file_name,
    export_plotobj = FALSE,
    plot = NULL,
    device = NULL,
    path = NULL,
    scale = 1,
    width = NA,
    height = NA,
    units = c("in", "cm", "mm", "px"),
    dpi = 300,
    limitsize = TRUE,
    ...,
    align = "none",
    axis = "none",
    nrow = NULL,
    ncol = NULL,
    rel_widths = 1,
    rel_heights = 1,
    labels = NULL,
    label_size = 14,
    label_fontfamily = NULL,
    label_fontface = "bold",
    label_colour = NULL,
    label_x = 0,
    label_y = 1,
    hjust = -0.5,
    vjust = 1.5,
    scale_grid = 1,
    greedy = TRUE,
    byrow = TRUE) {

  if (is.null(plot)) {
    message("No plot object provided. Skipping plot export.")
    return(invisible(NULL))  # Stop further execution
  }




  format <- sub('.*\\.', '', tolower(file_name))

  if (!is.null(device) && !(device %in% c("eps", "ps", "tex", "pdf", "jpeg", "tiff", "png", "bmp", "svg", "wmf"))) {
    stop("Unsupported device. Supported devices are 'eps', 'ps', 'tex', 'pdf', 'jpeg', 'tiff', 'png', 'bmp', 'svg', and 'wmf'.")
  }

  if (is.null(device)) {
    device <- ifelse(format %in% c("eps", "ps", "tex", "pdf", "jpeg", "tiff", "png", "bmp", "svg", "wmf"), format, stop("Unsupported file format or device. Supported formats are 'eps', 'ps', 'tex', 'pdf', 'jpeg', 'tiff', 'png', 'bmp', 'svg', and 'wmf'."))
  }

  message(paste0(file_name, " will be exported in the following format: ", width, "X", height, " using ", device, " device."))

  if(inherits(plot, "ggplot")){

    ggsave2(filename = file_name,
            plot = plot,
            device = device,
            path = path,
            scale = scale,
            width = width,
            height = height,
            units = units,
            dpi = dpi,
            limitsize = limitsize,
            ...)

    #return("Plot export completed successfully.")


  } else if (is.list(plot) && all(sapply(plot, function(x) inherits(x, "ggplot")))) {

    message("A list of plots was provided.Arranging multiple plots into a grid layout")

    plot <- plot_grid(
      plotlist = plot,
      align = align,
      axis = axis,
      nrow = nrow,
      ncol = ncol,
      rel_widths = rel_widths,
      rel_heights = rel_heights,
      labels = labels,
      label_size = label_size,
      label_fontfamily = label_fontfamily,
      label_fontface = label_fontface,
      label_colour = label_colour,
      label_x = label_x,
      label_y = label_y,
      hjust = hjust,
      vjust = vjust,
      scale = scale_grid,
      greedy = greedy,
      byrow = byrow
    )

    ggsave2(filename = file_name,
           plot = plot,
           device = device,
           path = path,
           scale = scale,
           width = width,
           height = height,
           units = units,
           dpi = dpi,
           limitsize = limitsize,
           ...)

    #return("Plot export completed successfully.")


  }else {
    stop("Unsupported plot format. Please provide either a single ggplot object or a list of ggplot objects.")
  }

  if(export_plotobj){

    if(is.null(path)){
      path <- getwd()
    }

    filename_without_extension <- tools::file_path_sans_ext(file_name)
    new_filename <- paste0(filename_without_extension, ".rds")
    saveRDS(plot, file = paste0(path,"/",new_filename))
  }

  return("Plot export completed successfully.")
}

Try the Virusparies package in your browser

Any scripts or data that you put into this service are public.

Virusparies documentation built on April 12, 2025, 1:48 a.m.