R/GlobalPlot.R

Defines functions GlobalPlot

Documented in GlobalPlot

#' Plot global admixture proportions
#'
#' @param Prop
#' Matrix of admixture proportions of dimension
#' `N` (number of individuals) x `K` (number of groups)
#'
#' @return
#' A global admixture barplot as a ggplot object
#'
#' @description
#' This function generates an admixture barplot based on [ggplot2::ggplot()]
#' 
#'
#' @import tibble
#' @import dplyr
#' @import tidyr
#' @import ggplot2
#' @importFrom magrittr %>%
#'
#' @seealso
#' * [SimulatePop()] to simulate a polyploid admixed population.
#' * [AdmixGlobal()] to perform global (genome-wide) admixture inference and 
#' generate the `Prop` object.
#'
#' @export
#'
#' @examples
#' ## Simulate a polyploid admixed population
#' DataSim <- SimulatePop(K=3L, N=10L, P=6L, M=50L, C=5L, L=10L, Seed=123, NbThreads=1)
#'
#' ## Perform global admixture inference
#' ResGlobalAdmix <- AdmixGlobal(Geno=DataSim$Geno, K=3, Verbose=FALSE, NbThreads=1)
#'
#' ## Admxiture barplot
#' GlobalPlot(ResGlobalAdmix$Prop)
GlobalPlot <- function(Prop){
  ## Checks
  stopifnot("Prop must be a numeric matrix" =
              is.matrix(Prop) && is.numeric(Prop))
  stopifnot("Prop must have row names" =
              !is.null(rownames(Prop)))
  stopifnot("Prop must have column names" =
              !is.null(colnames(Prop)))

  ## Define global variable for tidy operations
  Individuals <- NULL
  Proportion <- NULL
  Group <- NULL

  ## Format dataframe
  Prop_df <- Prop %>% as_tibble %>%
    mutate(Individuals = rownames(Prop)) %>%
    pivot_longer(cols = !Individuals,names_to = "Group",values_to = "Proportion") %>%
    mutate(Group = factor(Group,levels=colnames(Prop))) %>%
    mutate(Individuals = factor(Individuals, levels=rownames(Prop)))

  ## Barplot
  p <- ggplot(Prop_df,aes(x = Individuals, y = Proportion, fill = Group)) +
    scale_y_continuous(expand=expansion(mult = c(0,0))) +
    scale_x_discrete(expand=expansion(mult = c(0,0))) +
    geom_bar(stat="identity",position="stack",width = 1,alpha=0.7) +
    theme_bw() +
    scale_fill_brewer(palette = "Set1")+
    theme(axis.text.x = element_text(angle = 90, vjust = 0.3, hjust=1,size = 8),
          panel.grid = element_blank(),
          axis.text.y = element_text(size=6))

  ## Outputs
  return(p)
}

Try the AdmixPoly package in your browser

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

AdmixPoly documentation built on June 18, 2026, 1:06 a.m.