R/chord.R

Defines functions chordPlot

chordPlot <- function(enrichdf, nRows = 10, ont=NULL,  orderby=NULL) {
  if(! "dplyr" %in% .packages()) require("dplyr")
  if(! "tidyr" %in% .packages()) require("tidyr")
  if(! "chordiag" %in% .packages()) require("chorddiag")

  name <- match.arg(names(enrichdf)[1], c("Pathway", "Term"))

  if(dim(enrichdf)[2]==7){
    if(!is.null(ont)){
      enrichdf = enrichdf[enrichdf$Ont==ont, ]
    } else{
      stop("Ontology must be provided if enrichdf is customGO object")
    }
  }

  if(!is.null(orderby)){
    orderby = match.arg(orderby, c("DE", "P.DE", "N", name))
    if(orderby=="P.DE" | orderby == name){
      enrichdf <- enrichdf %>% arrange(get(orderby))
    } else{ enrichdf <- enrichdf %>% arrange(desc(get(orderby)))}
  }

  kgg <- enrichdf
  n <- nRows

  tmp <- kgg[1:n, c(name, "genes") ]
  tmp2 <- tmp %>% separate_rows(genes, convert = TRUE)
  kk <- tidyr::pivot_wider(tmp2, names_from = name, values_from = genes)

  ns <- NULL
  nd <- NULL
  for (i in seq(1, dim(kk)[2])) {
    pt <- unlist(kk[1, i][[1]])
    for (j in seq(1, dim(kk)[2])) {
      ns <-
        append(ns, length(intersect(unlist(kk[1, i][[1]]), unlist(kk[1, j][[1]]))))
      if (i != j) {
        pt <- pt[!(pt %in% unlist(kk[1, j][[1]]))]
      }
    }
    nd <- append(nd, length(pt))
  }
  m <- matrix(ns, nrow = dim(kk)[2])
  diag(m) <- nd
  dimnames(m) <- list(have = names(kk), prefer = names(kk))

  p <- chorddiag(
    m,
    groupnamePadding = 20,
    margin = 100,
    groupColors = colorRampPalette(RColorBrewer::brewer.pal(11, "Spectral"))(n),
    showGroupnames = FALSE,
    tooltipFontsize = 12,
    showTicks = FALSE
  )
  return(p)
}
fpsanz/enrichGene documentation built on Feb. 20, 2020, 3:20 a.m.