---
title: "Bioinformatic Analysis of RNA-sequencing <br> <br> R Introduction : Plots"
subtitle: "Allison Burns, Maxime Jan, Linda Mhalla, Christian Iseli, Nicolas Guex"
output:
  ioslides_presentation:
    css: ../css/styles.css
    incremental: no
    widescreen: true
    toc: yes
    transition: faster
---


```{r,echo=F,warning=F,message=F}
if (!require("scales")) install.packages("scales")
if (!require("ggplot2")) install.packages("ggplot2")
if (!require("gplots")) install.packages("gplots")
if (!require("patchwork")) install.packages("patchwork")
if (!require("ggrepel")) install.packages("ggrepel")
```


# General plot function {.pre}

## Scatterplot {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

```{r,echo=F}
set.seed(1)
```


```{r,fig.height=4,fig.width=4}
MyVector<-rnorm(10)
plot(MyVector,main="Scatterplot",pch=1)
```

:::
::: {}

You can customise the type of points you want using e.g. pch=22


```{r,echo=F,warning=F,fig.height=5,fig.width=4}
grid <- expand.grid(1:5, 6:1)
plot(grid, pch = 0:30, cex = 2.5,
     yaxt = "n", xaxt = "n",
     ann = FALSE, xlim = c(0.5, 5.25),
     ylim = c(0.5, 6.5))

grid2 <- expand.grid(seq(0.6, 4.6, 1), 6:1)
text(grid2$Var1[1:26], grid2$Var2[1:26], 0:25)
```

:::
::::

## {.pre}


:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

You can customize also color

```{r,fig.height=4,fig.width=4}
plot(MyVector,main="Scatterplot",pch=19,col=1)
```

:::
::: {}

```{r,echo=F,warning=F,fig.height=5,fig.width=4}
grid <- expand.grid(1:5, 6:1)
plot(grid, pch = 19, cex = 2.5, col=1:30,
     yaxt = "n", xaxt = "n",
     ann = FALSE, xlim = c(0.5, 5.25),
     ylim = c(0.5, 6.5))

grid2 <- expand.grid(seq(0.6, 4.6, 1), 6:1)
text(grid2$Var1[1:26], grid2$Var2[1:26], 0:25)
```

or use name like:

```{r,eval=F}
plot(MyVector,main="Scatterplot",pch=19,col="red")
```


:::
::::

## {.pre}

color names

```{r,echo=F,fig.height=6,fig.width=8}
# No margin around chart
par(mar=c(0,0,0,0))

# Empty chart
plot(0, 0, type = "n", xlim = c(0, 1), ylim = c(0, 1), axes = FALSE, xlab = "", ylab = "")

# Settings
line <- 25
col <- 5

# Add color background
rect(  
  rep((0:(col - 1)/col),line) ,  
  sort(rep((0:(line - 1)/line),col),decreasing=T),   
  rep((1:col/col),line) , 
  sort(rep((1:line/line),col),decreasing=T),  
  border = "white" , 
  col=colors()[seq(1,line*col)])

# Color names
text(  
  rep((0:(col - 1)/col),line)+0.1 ,  
  sort(rep((0:(line - 1)/line),col),decreasing=T)+0.015 , 
  colors()[seq(1,line*col)]  , 
  cex=1)
```


## Use factor for color {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

You can use factors to define your color

```{r,echo=F}
set.seed(1)
MyDataFrame<-data.frame(Genes=paste("Gene",seq(1:100),sep="_"),
                        FoldChange=rnorm(100),
                        pvalue=rbeta(100,.3,1))
```


```{r}
head(MyDataFrame)
```

:::
::: {}

```{r,fig.width=4,fig.height=4}
plot(MyDataFrame$FoldChange,-log10(MyDataFrame$pvalue),
     pch=19,cex=.5,
     col=c("black","red")[(MyDataFrame$pvalue < 0.05) +1])
abline(h=-log10(0.05))

legend("topright", legend = c("P>0.05","P<0.05"),
pch = 19, col = 1:2,)
```

:::
::::

## Options for plots {.pre}


before plot:

- Add e.g. *par(mfrow=c(2,1))* to have 2 plot (2 row, 1 column)
- Add e.g. *par(mar=c(5.1,4.1,4.1,2.1)* to change margin

plot option:

- *type="p"* or *type="l"* for points for lines
- *xlim=c()*, *ylim=c()* to set limits in the plots
- *pch* for the type of point you want
- *col* for color
- *lty* for linetype
- *lwd* for line width
- *main* for title
- *ylab* and *xlab* for axis name

<br>
after plot:

- *abline(a,b)* to add some lines (using y=ax+b)
- *points()* to add some points
- *lines()* to add some lines


## {.pre}

Example

```{r ,fig.width=6,fig.height=3}
data(iris)
par(mar=c(5,5,1,1))
par(mfrow=c(1,2))
plot(iris$Sepal.Length,iris$Sepal.Width, col=as.factor(iris$Species),
     pch=as.numeric(as.factor(iris$Species))+16,xlab="Sepal Length",
     ylab="Sepal Width",main="Sepal")

plot(iris$Petal.Length,iris$Petal.Width, col=as.factor(iris$Species),
     pch=as.numeric(as.factor(iris$Species))+16, xlab="Petal Length",
     ylab="Petal Width",main="Petal")
```

## Barplot

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

```{r}
iris_mean_sepal_width<-aggregate(
  iris$Sepal.Width,list(iris$Species),
  mean)

iris_mean_sepal_width
```

:::
::: {}

```{r,fig.width=4,fig.height=5}
barplot(iris_mean_sepal_width$x,
        horiz=TRUE,
        names.arg = iris_mean_sepal_width$Group.1)
```

:::
::::

## Histogram

you can use the library scales to add some transparency to color using *alpha()*

```{r}
library(scales)
hist(iris$Sepal.Width[iris$Species == "setosa"],col=alpha("red",.5))
hist(iris$Sepal.Width[iris$Species == "versicolor"],add=T,col=alpha("blue",.5))
```

## boxplot {.pre}

:::: {style="display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 50px; "}
::: {}

You can simply create boxplot with the *boxplot()* function. It will create a boxplot per column in your data frame


```{r}
head(iris,n=3)
```


```{r,fig.width=4,fig.height=2}
par(mar=c(3,4,1,1))
boxplot(iris)
```


:::
::: {}

Or you can use the linear model annotation

```{r,echo=F}
MyMetadata<-data.frame("Gene_Expression"=rnorm(9),
                       "Treatment"=rep(c("Control","A_vehic","Treatment"),each=3),
                       "Batch" = rep(c("B1","B2","B3"),3))
head(MyMetadata,n=4)
```

```{r,fig.width=4,fig.height=2}
par(mar=c(3,4,1,1))
boxplot(Gene_Expression~Treatment,data=MyMetadata)
```



:::
::::


## Heatmaps {.pre}

Using gplots package, we can plot heatmap and row color

```{r,fig.width=8,fig.height=4}
iris_scaled<-apply(iris[,1:4],2,scale)
heatmap.2(t(iris_scaled),col=redgreen(75),trace="none",
          ColSideColors = c("black","red","green")[factor(iris$Species)],
          cexRow = .8,)
```


## Even more complex with ComplexHeatmap

```{r, echo=FALSE, out.width="75%"}
knitr::include_graphics("image/Complexheatmap.png")
```


# ggplot2 {.pre}

## 

Another way to have nicer plot, is to use the ggplot2 package: 


```{r,fig.height=4,fig.width=4}
library(ggplot2)

ggplot(aes(FoldChange,-log10(pvalue),color=as.factor(pvalue<0.05)),data=MyDataFrame)+
  geom_point()+
  scale_color_manual("P<0.05",values=c("FALSE"="black","TRUE"="red"))+
  theme_bw()
```

## What you need to make ggplot2 {.pre}

- data.frame of your data

```{r}
head(MyDataFrame)
```


- Specify easthetic mappings: (which columns of your data.frame will be used for what)
  - You can specify: x,y axes (position)
  - color
  - fill
  - groups
  - shape
  - size
  - transparency
  
## {.pre}

```{r}
MyPlot <- ggplot(aes(FoldChange,-log10(pvalue),color=as.factor(pvalue<0.05)),data=MyDataFrame)
```

- Them you add some layers (how data should be represented)
  - it can be point: geom_point()
  - lines: geom_lines()
  - histogram, polygon, boxplot, violin_plot etc...

```{r}
MyPlot <- MyPlot + geom_point()
```

- Then you can rescale everything, here just for color:
  - scale_color_manuals()
  - scale_color_continuous()
  - scale_color_gradientn(), but see also scale_color_gradient2() and scale_color_gradient()
  - scale_colour_brewer(palette = "Set1")
  - scale_color_viridis_c()

Here we rescaled color

```{r}
MyPlot <- MyPlot + scale_color_manual(values=c("FALSE"="black","TRUE"="red"))
```

Finally we apply a theme:

```{r}
MyPlot <- MyPlot + theme_bw()
```


## Some tips: {.pre}

- Combine plots using package: patchwork
- *+ylim()* and *+xlim()* sometimes will remove value, you can also use *coord_cartesian()*
- You can use *+facet_grid(~yourgroup)* to plot multiple groups
- for labels, you can use labs:
- Add some lines using geom_hline, geom_vline
- Add some text using ggrepel package for non-overalping text
- With theme, you can change font size
- Use "annotate()" to add extra point or lines not present in your original data


## 

```{r,fig.height=3, fig.width=6}
(MyPlot + theme(legend.position = "none")) | # | tell patchwork to plot side by side plot
  
  MyPlot + labs(title = "DE expression",subtitle = "Cortex",x="Fold-Change",y="-log10 Pvalue", color="Significant") + 
    geom_hline(yintercept = -log10(0.05))+geom_text_repel(aes(label=Genes),size=2) + 
    theme( plot.title=element_text(size=10,face="bold"),
           axis.text=element_text(size=15),
           axis.title=element_text(size=10,face="bold"))
```


## Example of combined plots

```{r, echo=FALSE, out.width="35%"}
knitr::include_graphics("image/Exampleggplot2.png")
```