R/pie_plot_of_annotated_regions.R

Defines functions annotation_pie

Documented in annotation_pie

###pie plot of annotation regions
#' A pie plot of annotation regions frequencies generator
#'
#' A function that allows you to plot pie plot showing the frequencies of annotation regions (e.g. promoter, exon, 3'UTR, etc)
#' @param samples a list of data frames of annotated peaks
#' @param plot_dir the directory in which you want the plots, default = "plots"
#' @keywords pie
#' @import tidyverse gridExtra ggsci
#' @export
#' @examples
#' annotation_pie(sample, plot_dir)
annotation_pie <- function(samples, plot_dir = "plots"){
  count <- 0
  dir.create(file.path(plot_dir), showWarnings = FALSE)
  pie <- lapply(samples, function(condition){
    by_region <- condition %>%
      select(GenomicAnnotation) %>%
      mutate(brief_annotation = sub(" .*", "", GenomicAnnotation)) %>%
      group_by(brief_annotation) %>%
      select(brief_annotation) %>%
      mutate(brief_annotation = fct_recode(as.factor(brief_annotation),
                                           "3'UTR" = "3'",
                                           "5'UTR" = "5'"
      )) %>%
      summarise(count = n()) %>%
      mutate(prop = count / sum(count) * 100) %>%
      mutate(ypos = cumsum(prop)- 0.5*prop )
  })
  pl <- lapply(pie, function(condition){
    ggplot(condition, aes(x="", y=prop, fill = brief_annotation)) +
      geom_bar(stat="identity", width=1, col = pal_npg()(length(condition$brief_annotation))) +
      coord_polar("y", start=0) +
      ggtitle(names(samples)[count]) +
      theme_void() +
      labs(fill="Legend") +
      scale_fill_npg("nrc", alpha = 0.8)
  })
  pdf(file.path(plot_dir, "annotation_pie.pdf"))
  do.call(grid.arrange, c(pl, nrow = round(length(samples)/2)))
  dev.off()
}
riccardo-trozzo/BlissR documentation built on Aug. 1, 2020, 12:23 a.m.