---
title: "Iris PCA Example"
author: "Dan Veltri"
date: "9/9/2019"
output:
  html_document: default
---

```{r setup, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Iris Data Principal Components Analysis

This is a built-in data set for R from Fisher and Anderson. It contains four measurements (cols 1-4) for 50 samples each of three different iris spp. (col 5). Let's run PCA on the data and see if we can visualize view it in a 2D plot:

```{r iris-pca}
data('iris')
head(iris) # see what it looks like
iris.x = iris[,1:4] # measurements
iris.y = iris[,5] # our response labels

iris.pca = prcomp(iris.x, scale=TRUE, center=TRUE)
summary(iris.pca)
plot(iris.pca,main="Proportion of Variance for PCs 1-4",xlab="PCs 1-4")
```

It looks like the cumulative variance for PC1 and PC2 is greater than 95%. Let's use these to make our plot.
```{r iris-pca-2d-plot}
plot(iris.pca$x[,1], iris.pca$x[,2], col=iris.y, main="2D PCA Plot of Iris Data",xlab="PC1 (Variance 73%)",ylab="PC2 (Variance 23%)")
```

## Plotly 2D

We can see the three species cluster above, but wouldn't it be nice to hover over a point and learn more about it? We can do this with Plotly!

```{r iris-pca-2d-plotly, echo=FALSE}
library(plotly)

# Plotly works better with data frames
iris.pca.df = data.frame("PC1"=as.matrix(iris.pca$x[,1]), "PC2"=iris.pca$x[,2], "Species"=iris.y)

plot_ly(iris.pca.df,x=~PC1, y=~PC2,
        type='scatter',
        mode = 'markers', # could set this to 'text' to show sample names etc.
        symbol = ~Species,
        symbols = c('circle','x','o'),
        color = ~Species,
        colors = c('black','red','green'),
        text = ~Species,
        marker = list(size = 10)) %>%
  layout(title="2D PCA Plot of Iris Data",
         xaxis=list(title='PC1 (Variance 73%)'),
         yaxis=list(title='PC2 (Variance 23%)'))
```

## Challenge: Now try to make a 3D Plot!
```{r iris-pca-3d-plotly}
library(plotly)

# We'll add the 3rd PC to the data frame
iris.pca.df = data.frame("PC1"=as.matrix(iris.pca$x[,1]), "PC2"=iris.pca$x[,2], "PC3"=iris.pca$x[,3], "Species"=iris.y)

# YOUR CODE HERE!

```


