---
title: "RNAseq Visualization Automation"
output: 
  rmarkdown::html_vignette:
    toc: true
    fig_width: 6
    fig_height: 4

vignette: >
  %\VignetteIndexEntry{RNAseq Visualization Automation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---


# RNAseq Visualization Automation
&nbsp;

Install RVA from GitHub
```{r eval=FALSE}
devtools::install_github("THERMOSTATS/RVA_prod")
```
&nbsp;

Load package for use
```{r message=FALSE, warning=FALSE}
library(RVA)
```
&nbsp;

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, rows.print=25, comment = "")

options(
  ggplot2.continuous.colour = 'viridis',
  ggplot2.continuous.fill = 'viridis'
)
```



# Load Example Data
Let's load a summary statistics tables and combine them into a list named **d1**.
&nbsp;

```{r }
df <- RVA::Sample_summary_statistics_table
df1 <- RVA::Sample_summary_statistics_table1 
d1 <- list(df, df1)
```
&nbsp;

This is head of the first summary statictic table present in the list:
&nbsp;

```{r, echo=FALSE}
knitr::kable(head(d1[[1]]))
```
&nbsp;


The row names are gene id, the supported gene id can be one of: ACCNUM, ALIAS, ENSEMBL, ENSEMBLPROT, ENSEMBLTRANS, ENTREZID, ENZYME, EVIDENCE, EVIDENCEALL, GENENAME, GO, GOALL, IPI, MAP, OMIM. For the provided sample datasets in this package we only have ENSEMBL id's for gene id type.
&nbsp;

# Functions  


## Cutoff Plot 
&nbsp;

This function checks the number of differencialy expressed (DE) genes at different cutoff combinations. It process summary statistics table generated by differential expression analysis like limma or DESeq2, as input data, to evaluate the number of differntially expressed genes with different FDR and fold change cutoff. 
&nbsp;

Below are the default parameters for plot_cutoff. You can change them to modify your output. Use `help(plot_cutoff)` to learn more about the parameters.
&nbsp;
```{r ,eval=FALSE}
plot_cutoff(data = data,
  comp.names = NULL,
  FCflag = "logFC",
  FDRflag = "adj.P.Val",
  FCmin = 1.2,
  FCmax = 2,
  FCstep = 0.1,
  p.min = 0,
  p.max = 0.2,
  p.step = 0.01,
  plot.save.to = NULL,
  gen.3d.plot = TRUE,
  gen.plot = TRUE)
```
&nbsp;


### 1.1 Cutoff Plot - Input: a data frame.
```{r}
cutoff.result <- plot_cutoff(data = df,
                       gen.plot = TRUE,
                       gen.3d.plot = TRUE)
```
&nbsp;

The result object **cutoff.result** takes a data frame as an input data and contains 3 objects:
&nbsp;


**1.** A table that summarizes the number of DE genes under threshold combination
&nbsp;
```{r, eval=FALSE}
head(cutoff.result[[1]])
```

```{r, echo= FALSE}
knitr::kable(head(cutoff.result[[1]]))
```
&nbsp;

**2.** A 3D plotly object, where the x-axis is Fold change threshold, y-axis is FDR cutoff, and z-axis is the number of DE genes under the x,y combination:
&nbsp;

```{r, warning=FALSE, eval=FALSE}
cutoff.result[[2]]
```
&nbsp;

**3.** A plot to visualize it:

```{r, warning=FALSE}
cutoff.result[[3]]
```
&nbsp;


**Saving figures**
&nbsp;

Figures can be saved using two approaches:
&nbsp;

**1.** Using imbedded fucntion with predetermined dpi
&nbsp;

```{r, eval=FALSE}
plot_cutoff(data = df,
            plot.save.to = "cut_off_selection_plot.png")
```
&nbsp;

**2.** Using ggsave from the ggplot2 library with option to customize the width, height and dpi.
&nbsp;

```{r, eval=FALSE}
library(ggplot2)
ggsave("cut_off_selection_plot.png", cutoff.result[[3]], width = 5, height = 5, dpi = 300)
```
&nbsp;

&nbsp;


### 1.2 Cutoff Plot - Input: a list.
&nbsp;

```{r, message=FALSE}
cutoff.result.list <- plot_cutoff(data = d1, 
                                  comp.names = c('a', 'b'))
```
&nbsp;

The result object **cutoff.result.list** takes a list as an input data and contains 2 objects:
&nbsp;

**1.** A table that summarizes the number of DE genes under threshold combination for each of the data frames in the list.
&nbsp;

```{r, eval=FALSE}
head(cutoff.result.list[[1]])
```

```{r, echo=FALSE}
knitr::kable(head(cutoff.result.list[[1]]))
```
&nbsp;

**2.** A plot to visualize it. A 3D plotly object is not created for a list input data. 
&nbsp;

```{r}
cutoff.result.list
```
&nbsp;

**Saving figures**
&nbsp;

Figures can be saved using two approaches:
&nbsp;

**1.** Using imbedded fucntion with predetermined dpi
&nbsp;

```{r, eval=FALSE}
plot_cutoff(data = d1,
            comp.names = c("A", "B"),
            plot.save.to = "cut_off_list_plot.png")
```
&nbsp;

**2.** Using ggsave from the ggplot2 library with option to customize the width, height and dpi.
&nbsp;

```{r, eval=FALSE}
library(ggplot2)
ggsave("cut_off_list_plot.png", cutoff.result.list, width = 5, height = 5, dpi = 300)
```
&nbsp;

&nbsp;

&nbsp;


## QQ Plot
&nbsp;

This is the function to generate a qqplot object with confidence interval from the input data. The input data is a summary statistics table or a list that contains multiple summary statistics tables from limma or DEseq2, where each row is a gene.
&nbsp;


### 2.1 QQ Plot - Input: a data frame.
&nbsp;

```{r, results='hide'}
qq.result <- plot_qq(df)
qq.result
```
&nbsp;

**Saving figures**
&nbsp;

Figures can be saved using two approaches:
&nbsp;

**1.** Using imbedded fucntion with predetermined dpi
&nbsp;

```{r, eval=FALSE}
plot_qq(data = df,
        plot.save.to = "qq_plot.png")
```
&nbsp;

**2.** Using ggsave from the ggplot2 library with option to customize the width, height and dpi.
&nbsp;

```{r, eval=FALSE}
library(ggplot2)
ggsave("qq_plot.png", qq.result, width = 5, height = 5, dpi = 300)
```
&nbsp;

### 2.2 QQ Plot - Input: a list.
&nbsp;

**plot_qq** function can also take a list as an input data, but requires *comp.names* to be specified. The result object is a set of qq plots for each of the data frames in the list.
&nbsp;

```{r, results='hide'}
qq.list.result <- plot_qq(data = d1, 
        comp.names = c('A', 'B'))
qq.list.result
```
&nbsp;

**Saving figures**
&nbsp;

Figures can be saved using two approaches:
&nbsp;

**1.** Using imbedded fucntion with predetermined dpi
&nbsp;

```{r, eval=FALSE}
plot_qq(data = d1,
        comp.names = c("A", "B"),
        plot.save.to = "qq_list_plot.png")
```
&nbsp;

**2.** Using ggsave from the ggplot2 library with option to customize the width, height and dpi.
&nbsp;

```{r, eval=FALSE}
library(ggplot2)
ggsave("qq_list_plot.png", qq.list.result, width = 5, height = 5, dpi = 300)
```
&nbsp;

&nbsp;

&nbsp;


## Volcano Plot
&nbsp;

This is the function to process the summary statistics table generated by differential expression analysis like limma or DESeq2 and generate the volcano plot with the option of highlighting the individual genes or gene set of interest (like disease-related genes from Disease vs Healthy comparison). The input data is a summary statistics table or a list that contains multiple summary statistics tables from limma or DEseq2, where each row is a gene.
&nbsp;

Below are the default parameters for plot_volcano. You can change them to modify your output. Use `help(plot_volcano)` to learn more about the parameters.
&nbsp;
```{r ,eval=FALSE}
plot_volcano(
  data = data,
  comp.names = NULL,
  geneset = NULL,
  geneset.FCflag = "logFC",
  highlight.1 = NULL,
  highlight.2 = NULL,
  upcolor = "#FF0000",
  downcolor = "#0000FF",
  plot.save.to = NULL,
  xlim = c(-4, 4),
  ylim = c(0, 12),
  FCflag = "logFC",
  FDRflag = "adj.P.Val",
  highlight.FC.cutoff = 1.5,
  highlight.FDR.cutoff = 0.05,
  title = "Volcano plot",
  xlab = "log2 Fold Change",
  ylab = "log10(FDR)"
)
```
&nbsp;

### 3.1 Volcano Plot - Input: a data frame. 
&nbsp;

```{r message=FALSE, results='hide', warning=FALSE}
plot_volcano(data = df)
```
&nbsp;

### 3.2 Volcano Plot - Input: a list.
&nbsp;

Volcano Plot can also take a list as an input data with specified **comp.name** for each data frame.
&nbsp;

```{r message=FALSE, results='hide', warning=FALSE}
plot_volcano(data = d1, 
             comp.names = c('a', 'b'))
```
&nbsp;

### 3.3 Highlight genes of interest in the volcano plot
&nbsp;

You can highlight gene sets (like disease related genes from a Disease vs Healthy comparison).
&nbsp;

The gene set to be highlighted in the volcano plot can be spesified in two ways:
&nbsp;

**1.** A summary statistics table with the highlighted genes as row names (the gene name format needs to be consistent with the main summary statistics table). For example, this summary statistics table could be the statistical analysis output from a Disease vs Healthy comparison (only containing the subsetted significant genes).
&nbsp;

**2.** One or two vectors consisting of gene names. The gene name format needs to be consistent with the main summary statistics table. It can be set by the parameters highlight.1 and highlight.2. For example, you can assign the up-regulated gene list from the Disease vs Healthy comparison to highlight.1 and down-regulated gene list from the comparison to highlight.2.
&nbsp;

**Example using option 1** (use summary statistics table's row name to highlight genes):
&nbsp;

```{r}
#disease gene set used to color volcanoplot
dgs <- RVA::Sample_disease_gene_set 
```
&nbsp;

```{r ,eval=FALSE}
head(dgs)
```

```{r ,echo=FALSE}
knitr::kable(head(dgs))
```
&nbsp;



You can also specify the range of the plot by *xlim* and *ylim*.
&nbsp;

```{r message=FALSE,warning=FALSE}
plot_volcano(data = df,
             geneset = dgs,
             upcolor = "#FF0000",
             downcolor = "#0000FF",
             xlim = c(-3,3),
             ylim = c(0,14))
```
&nbsp;

By default, the genes which have positive fold change in the provided **geneset** parameter will be colored yellow, and negative fold will be colored  purple, this also can be changed by specifying *upcolor* and *downcolor*:
&nbsp;

```{r message=FALSE, warning=FALSE}
plot_volcano(data = d1,
             comp.names = c('a', 'b'),
             geneset = dgs,
             upcolor = "#FF0000",
             downcolor = "#0000FF",
             xlim = c(-3,3),
             ylim = c(0,14))
```
&nbsp;

**Example with option 2**
You can also specify the color of **highlight.1** with *upcolor* parameter and
**highlight.2** with *downcolor* parameter.
&nbsp;

```{r message=FALSE,warning=FALSE}
volcano.result <- plot_volcano(data = df,
                  highlight.1 = c("ENSG00000169031.19","ENSG00000197385.5","ENSG00000111291.8"),
                  highlight.2 = c("ENSG00000123610.5","ENSG00000120217.14", "ENSG00000138646.9", "ENSG00000119922.10","ENSG00000185745.10"),
                  upcolor = "darkred",
                  downcolor = "darkblue",
                  xlim = c(-3,3),
                  ylim = c(0,14))
volcano.result
```
&nbsp;

**Saving figures**
&nbsp;

Figures can be saved using two approaches:
&nbsp;

**1.** Using imbedded fucntion with predetermined dpi
&nbsp;

```{r, warning=FALSE, eval=FALSE}
plot_volcano(data = df,
             geneset = dgs,
             plot.save.to = "volcano_plot.png")
```
&nbsp;

**2.** Using ggsave from the ggplot2 library with option to customize the width, height and dpi.
&nbsp;

```{r, eval=FALSE}
library(ggplot2)
ggsave("volcano_plot.png", volcano.result, width = 5, height = 5, dpi = 300)
```
&nbsp;

&nbsp;

&nbsp;


## Pathway analysis plot
&nbsp;

This is the function to do pathway enrichment analysis (and visualization) with rWikiPathways (also KEGG, REACTOME & Hallmark) from a summary statistics table generated by differential expression analysis like limma or DESeq2. In directional enrichment analysis, the sign(positive/negative) indicates the direction of the enrichement, not the mathematical sign of -log10(FDR), for example, the positive sign indicate the up-regulated genes in geneset is over-represented in all the genes in the genome are up-regulated.
&nbsp;

Below are the default parameters for plot_pathway. You can change them to modify your output. Use `help(plot_pathway)` to learn more about the parameters.
&nbsp;
```{r ,eval=FALSE}
plot_pathway(
  data = df,
  comp.names = NULL,
  gene.id.type = "ENSEMBL",
  FC.cutoff = 1.3,
  FDR.cutoff = 0.05,
  FCflag = "logFC",
  FDRflag = "adj.P.Val",
  Fisher.cutoff = 0.1,
  Fisher.up.cutoff = 0.1,
  Fisher.down.cutoff = 0.1,
  plot.save.to = NULL,
  pathway.db = "rWikiPathways"
  )
```
&nbsp;


Our sample dataset provided in the package only contains ENSEMBL gene id types. Other types can be used by changing the parameter `gene.id.type = " id type"`. When inputing a single data frame for analysis, `comp.names` are not required. Currently we are using rWikiPathways as a database for enrichment analysis but this can be changed to KEGG, REACTOME, Hallmark or a static version of rWikiPathways by changing the parameter `pathway.db = "database name"`.
&nbsp;

```{r message=FALSE, warning=FALSE, results="hide"}
pathway.result <- plot_pathway(data = df, pathway.db = "Hallmark", gene.id.type = "ENSEMBL")
```
&nbsp;

### 4.1 Pathway analysis result is a list that contains 5 objects:
&nbsp;

**1.** Pathway analysis table with directional result (test up-regulated gene set and down-regulated gene set respectively).
&nbsp;

```{r eval=FALSE}
head(pathway.result[[1]])
```

```{r echo=FALSE}
knitr::kable(head(pathway.result[[1]]))
```
&nbsp;

**2.** Pathway analysis table with non-directional fisher's enrichment test result for all DE genes regardless of direction.
&nbsp;

```{r eval=FALSE}
head(pathway.result[[2]])
```

```{r echo=FALSE}
knitr::kable(head(pathway.result[[2]]))
```
&nbsp;

**3.** Pathway analysis plot with directional result.
&nbsp;

```{r}
pathway.result[[3]]
```
&nbsp;

**4.** Pathway analysis plot with non-directional result.
&nbsp;

```{r}
pathway.result[[4]]
```
&nbsp;

**5.** Pathway analysis plot with combined direaction and non-directional result.
&nbsp;

```{r}
pathway.result[[5]]
```
&nbsp;

**Saving figures**
&nbsp;

Figures can be saved using ggsave from the ggplot2 library.
&nbsp;

```{r eval=FALSE}
library(ggplot2)
ggsave("joint_plot.png",pathway.result[[5]], width = 5, height = 5, dpi = 300)
```
&nbsp;

### 4.2 Pathway analysis for the list of summary tables will result in a list that contains 4 objects:
&nbsp;

Pathways with list of data as input, the list can be replaced with `d1` from the top. When list inputs are given `comp.names` should be speicified in order to identify the comparison groups.
&nbsp;

```{r message=FALSE, warning=FALSE, results="hide"}
list.pathway.result <- plot_pathway(data = list(df,df1),comp.names=c("A","B"),pathway.db = "Hallmark", gene.id.type = "ENSEMBL")
```
&nbsp;

**1.** Pathway analysis table with directional result for all datasets submited.
&nbsp;

```{r eval=FALSE}
head(list.pathway.result[[1]])
```

```{r echo=FALSE}
knitr::kable(head(list.pathway.result[[1]]))
```
&nbsp;

**2.** Pathway analysis table with non directional result for all datasets submited.
&nbsp;

```{r eval=FALSE}
head(list.pathway.result[[2]])
```

```{r echo=FALSE}
knitr::kable(head(list.pathway.result[[2]]))
```
&nbsp;

**3.** Pathway analysis plot with directional result for list of summary tables.
&nbsp;

```{r}
list.pathway.result[[3]]
```
&nbsp;

**4.** Pathway analysis plot with non directional result for list of summary tables.
&nbsp;

```{r}
list.pathway.result[[4]]
```
&nbsp;

**Saving figures**
&nbsp;

Figures can be saved using ggsave from the ggplot2 library.
&nbsp;

```{r , eval=FALSE}
library(ggplot2)
ggsave("non-directional.png",pathway.result[[4]], width = 5, height = 5, dpi = 300)
```
&nbsp;


&nbsp;

&nbsp;


## Heatmap
&nbsp;

###  5.1 Heatmap
&nbsp;

You can plot a heatmap from raw data rather than a summary statistics
table. `plot_heatmap.expr` has the ability to
calculate average expression values and change from baseline. Importantly, 
these calculations do not calculate statistical signifance or correct for
confounding factors - they should not be used as statistical analyses but as
data overviews.
&nbsp;

For this, you need a count table and annotation table. The count table should
have the geneid as row names and the samples as column names. These column
names must match the `sample.id` column in your annotation file:
&nbsp;

```{r }
count <- RVA::count_table[,1:50]
```
&nbsp;

```{r , eval=FALSE}
count[1:6,1:5]
```

```{r ,echo=FALSE}
knitr::kable(count[1:6,1:5])
```
&nbsp;

```{r }
annot <- RVA::sample_annotation[1:50,]
```
&nbsp;

```{r ,eval=FALSE}
head(annot)
```

```{r ,echo=FALSE}
knitr::kable(head(annot))
```
&nbsp;



Plot a simple summary of expression values:
&nbsp;

Use `help(plot_heatmap.expr)` for more information on the parameters.
&nbsp;

```{r message=FALSE}
hm.expr <- plot_heatmap.expr(data = count, 
                             annot = annot,
                             sample.id = "sample_id",
                             annot.flags = c("day", "Treatment"),
                             ct.table.id.type = "ENSEMBL",
                             gene.id.type = "SYMBOL",
                             gene.names = NULL,
                             gene.count = 10,
                             title = "RVA Heatmap",
                             fill = "CPM",
                             baseline.flag = "day",
                             baseline.val = "0",
                             plot.save.to = NULL,
                             input.type = "count")
```
&nbsp;

The result of **plot_heatmap.expr** with **fill = CPM** contains 2 objects:
&nbsp;

**1.** Heat map 
&nbsp;

```{r, echo=FALSE}
hm.expr[[1]]
```
&nbsp;

**2.** A data frame of CPM values (fill = CPM in this example) for each geneid split by treatment group and time point.
&nbsp;

```{r, eval=FALSE}
head(hm.expr[[2]])
```


```{r, echo=FALSE}
knitr::kable(head(hm.expr[[2]]))
```
&nbsp;

**Customize the plot & Save the figure**
&nbsp;

Here is an example of how you can customize your output dimensions and save your new output using the png() function. Always make sure that the ComplexHeatmap library is loaded for the draw function.
&nbsp;

```{r results='hide', eval=FALSE}
library(ComplexHeatmap)
png("heatmap_plots2cp.png", width = 500, height = 500)
draw(hm.expr$gp)
dev.off()

```
&nbsp;

To calculate CFB from your input data, you must specify the baseline. The
heatmap shown below compares each treatment on days 14 and 28 to the respective
treatment on day 0.
&nbsp;

Use `help(plot_heatmap.expr)` for more information on the parameters.
&nbsp;

```{r message=FALSE}
hm.expr.cfb <- plot_heatmap.expr(data = count, 
                                 annot = annot,
                                 sample.id = "sample_id",
                                 annot.flags = c("day", "Treatment"),
                                 ct.table.id.type = "ENSEMBL",
                                 gene.id.type = "SYMBOL",
                                 gene.names = NULL,
                                 gene.count = 10,
                                 title = "RVA Heatmap",
                                 fill = "CFB",
                                 baseline.flag = "day",
                                 baseline.val = "0",
                                 plot.save.to = NULL,
                                 input.type = "count")

```
&nbsp;

The result of **plot_heatmap.expr** with **fill = CFB** contains 2 objects:

**1.** Heat map 
&nbsp;

```{r, echo=FALSE}
hm.expr.cfb[[1]]
```
&nbsp;

**2.** A data frame of change from baselines values (fill = CFB in this example) for each geneid split by treatment group and time point.
&nbsp;

```{r, eval=FALSE}
head(hm.expr.cfb[[2]])
```

```{r, echo=FALSE}
knitr::kable(head(hm.expr.cfb[[2]]))
```
&nbsp;

**Customize the plot & Save the figure**
&nbsp;

Here is an example of how you can customize your output dimensions. 
&nbsp;

```{r results='hide', eval=FALSE}
library(ComplexHeatmap)
png("heatmap_plots1cf.png", width = 500, height = 500)
draw(hm.expr.cfb$gp)
dev.off()
```
&nbsp;

&nbsp;

&nbsp;


## Gene expression
&nbsp;

### 6.1 Gene expression
&nbsp;


Let's load in the sample data provided in this package. Note that the count table containing data must have the
geneid set as the rownames and must have column names which match the
`sample.id` column of the annotation file.
&nbsp;

```{r }
anno <- RVA::sample_annotation
```
&nbsp;

```{r , eval=FALSE}
head(anno)
```

```{r , echo=FALSE}
knitr::kable(head(anno))
```
&nbsp;

```{r }
ct <- RVA::sample_count_cpm
```
&nbsp;

```{r ,eval=FALSE}
ct[1:6,1:5]
```

```{r ,echo=FALSE}
knitr::kable(ct[1:6,1:5])
```
&nbsp;

Below is a simple plot using the defaults. Further parameter changes can allow
you to change the log scaling, the input type to either cpm or count, and the genes selected
for plotting. The sample table we are using already has data points as CPM, so we will use CPM as our `input.type`. 
&nbsp;


Use `help(plot_gene)` for more information on the parameters.
&nbsp;

```{r}
gene.result <- plot_gene(ct, 
               anno,
               gene.names = c("AAAS", "A2ML1", "AADACL3", "AARS"),
               ct.table.id.type = "ENSEMBL",
               gene.id.type = "SYMBOL",
               treatment = "Treatment",
               sample.id = "sample_id",
               time = "day",
               log.option = TRUE,
               plot.save.to = NULL,
               input.type = "cpm")
```
&nbsp;

The result of **plot_gene** contains 2 objects:
&nbsp;

**1.** A gene expression plot that distinguishes log cpm gene expression for each geneid across the treatment groups and time points.
&nbsp;

```{r, echo = FALSE}
gene.result[[1]]
```
&nbsp;

**2.** A table that shows gene expression values by gene id, treatment group and time point with both sample ids and gene symbols.
&nbsp;

```{r, eval = FALSE}
head(gene.result[[2]])
```

```{r, echo = FALSE}
knitr::kable(head(gene.result[[2]]))
```
&nbsp;

**Customize the plot & Save the figure**
&nbsp;

Here is an example of how you can customize your output dimensions and save your new plot using the ggsave function. Always make sure that the ggplot2 library is loaded.
&nbsp;

```{r message=FALSE, eval=FALSE}
library(ggplot2)
ggsave(gene.result, "gene_plots1_4.png", device = "png", width = 100, height = 100, dpi = 200, limitsize = FALSE)
```
&nbsp;

&nbsp;

&nbsp;
