ctlab/fgsea

add rank plot for the GSEA plot

Closed this issue · 0 comments

Hello, recently I was making the GSEA plot; Maybe this can make the GSEA plot look more beautiful.

plotEnrichment2 <- function(pathways, pwayname, stats, gseaParam = 1, ticksSize = 0.2) {
  pd <- fgsea::plotEnrichmentData(
    pathway = pathways[[pwayname]], stats = stats,
    gseaParam = gseaParam
  )
  with(pd, ggplot(data = curve) +
    geom_line(aes(x = rank, y = ES),
      color = "blue"
    ) +
    geom_segment(data = ticks, mapping = aes(
      x = rank,
      y = -spreadES / 16, xend = rank, yend = spreadES / 16
    ), linewidth = ticksSize) +
    geom_hline(
      yintercept = posES, colour = "gray90",
      linetype = "dashed", linewidth = 0.2
    ) +
    geom_hline(
      yintercept = negES, colour = "gray90",
      linetype = "dashed", linewidth = 0.2
    ) +
    geom_hline(yintercept = 0, colour = "black") +
    scale_x_discrete(expand = expansion(0, 0)) +
    labs(y = "Enrichment Score")) +
    theme(
      panel.background = element_blank(),
      axis.title.x = element_blank(),
      panel.grid.major = element_line(color = "grey92"),
      text = element_text(size = 6)
    )
}


plotRank <- function(stats) {
  rankData <- data.table(ranks = 1:length(stats), y = fsort(stats, TRUE))
  ggplot(data = rankData) +
    scale_x_discrete(expand = expansion(0, 0)) +
    geom_segment(aes(x = ranks, y = 0, xend = ranks, yend = y), color = "gray60") +
    theme_classic(base_size = 6) +
    labs(x = "Rank", y = "Ranked List Metric")
}



plotGSEA <- function(fgseaRes, pathways, pwayname, stats, save = FALSE) {
  anno_text <- fgseaRes[.(pwayname), c(NES, padj), on = .(pathway)]
  p1 <- plotEnrichment2(pathways, pwayname, stats)
  p2 <- plotRank(stats)
  p3 <- patchwork::wrap_plots(p1, p2, heights = c(0.8, 0.3)) +
    patchwork::plot_annotation(
      title = pwayname,
      subtitle = sprintf("NES: %f, padj: %f", anno_text[[1]], anno_text[[2]]),
      theme = theme(
        plot.title = element_text(size = 8),
        plot.subtitle = element_text(size = 5, face = "italic")
      )
    )

  if (save) ggsave(paste0(pwayname, ".pdf"), width = 4, height = 2.7)

  p3
}

Then, we can plot the GSEA result:

library(fgsea)

data(examplePathways)
data(exampleRanks)

fgseaRes <- fgsea(pathways = examplePathways, 
                  stats    = exampleRanks,
                  minSize  = 15,
                  maxSize  = 500)
plotGSEA(
  fgseaRes, 
  pathways = examplePathways, 
  pwayname = "5991130_Programmed_Cell_Death", 
  stats = exampleRanks, 
  save = TRUE
)

The figure looks like this:

5991130_Programmed_Cell_Death.pdf