---
title: "Learn R - Monday PM"
output: html_notebook
---

This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code. 

Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Cmd+Shift+Enter*. 

Read in abalone data
```{r}
abalone <- read.csv("abalone.csv")
```


Plot 1 variable

```{r}
plot(abalone$length) # when we give plot only 1 numeric variable, it plots that variable against an index value (= row number)
```

We can more usefully plot a single numeric variable as a histogram.
```{r}
hist(abalone$length)
```

####Plot 2 Variables

Scatter Plot
```{r}
plot(abalone$whole.wt ~ abalone$rings) # Here I indicate graphing variables in the form of a formula, y ~ x
plot(abalone$rings, abalone$whole.wt)# I can also give variables in form of (x, y)
```
Boxplot
```{r}
boxplot(abalone$length ~ abalone$rings) # again I use formula to indicate what to plot on x and y
```

Bar Chart
  *For this we need mean value for each ring number category. We can calculate this using the `aggregate()` function.
```{r}
abalone.means <- aggregate(abalone, by = list(abalone$rings), FUN = mean) # when I run this code, because I give the function the whole data.frame, it tries to calculate the mean value for each variable by rings. However, one variable is categorical (sex) and thus a mean cannot be calculated, so we get a "non-numeric argument" warning for the 28 groups (we had 28 different ring number categories) of this variable. If you look at this variable (abalone.means$sex) you will see it contains all "NA", meaning missing data.

# We'll fix the above issue by specifying which variable we want the mean for, namely abalone$length:
abalone.means <- aggregate(abalone$length, by = list(abalone$rings), FUN = mean) # note that I could (& tyically do) leave off the argument name "FUN =" as R is expecting this variable in this position.

head(abalone.means) # note from this that my variable names are simply "Group.1" and "x"

```

```{r}
# Let's give my new abalone.means data.frame better variable names
names(abalone.means) <- c("rings", "mean_length") # if I assign new values to the result of the function names, then it will replace the variable names

#Now I can plot!
barplot(abalone.means$mean_length, names.arg = abalone.means$rings, ylab = "Mean Length") # Note this line in the handout (p. graphs 1-3) had a typo - there should be no round bracket after length variable.
# The names.arg argument in the barplot function indicates that the bars should be labelled with the values in the rings column of the file. The 'ylab' argument creates a y-axis label.
```

Dot chart
```{r}
dotchart(abalone.means$mean_length, labels = abalone.means$rings) # labels has the same purpose here as "names.arg" in barplot. Note that dotchart has axes reversed relative to a barplot.
```

Note that the output we get from the `plot()` function depends on the type of data we send to the function.
e.g., In the first plot of 2 variables we gave the function to numeric variables (whole.wt and rings) and plot returned a scatter plot.
What happens if we provide plot with a numeric variable and a factor variable?
```{r}
plot(abalone$length ~ abalone$sex) # if we give plot() a categorical x-value, it will give us a boxplot by default
```
```{r}
# If we do not want a boxplot, we can force plot() to give us a scatter plot by coercing the sex data to be a numeric variable using the function "as.numeric()"
plot(abalone$length ~ as.numeric(abalone$sex))
```

All of the commands we used above are **high-level** graph functions; i.e., they produce a graph in a graphics window.

R base graphics also has many **low-level** graph functions - these are functions that allow us to add annotations or more data to a graph.
Some of the most commonly used follow.

title
```{r}
plot(abalone$whole.wt ~ abalone$rings, ann = FALSE) #since I want to add titles and axes labels, I tell R to not use default plot annotations
title(main = "Abalone Age Estimate from Size", xlab = "Age (Number of Rings", ylab = ("Mass (mg)")) # note in handout (page graphs 1-5) missing comma after "Rings"
```

Add Points
```{r}
# First 2 lines as above, new 3rd line
plot(abalone$whole.wt ~ abalone$rings, ann = FALSE) 
title(main = "Abalone Age Estimate from Size", xlab = "Age (Number of Rings", ylab = ("Mass (mg)")) 
points(abalone$rings, abalone$shell.wt, pch = 2, col = "red") # plot a 2nd set of points on the same x,y scale using symbols of type 2 (triangles) and coloured red
```

Add legend
```{r}
#new 4th line
plot(abalone$whole.wt ~ abalone$rings, ann = FALSE, pch = 0, col = "blue", ylim = c(0,4)) # customize symbol and colour this time; also change y-axis scale to make room for legend 
title(main = "Abalone Age Estimate from Size", xlab = "Age (Number of Rings", ylab = ("Mass (mg)")) 
points(abalone$rings, abalone$shell.wt, pch = 2, col = "red")
legend("topleft", legend = c("Whole weight (mg)", "Shell weight (mg)"), pch = c(0,2), col = c("blue", "red"))
```

Now let's revise graph to give a second y-axis for shell weight, so it can be plotted on its own scale.
```{r}
par(mai=c(0.5,0.5,0.5,1)) # change margins to allow label on right y-axis margin
plot(abalone$whole.wt ~ abalone$rings) # customize symbol and colour this time; also change y-axis scale to make room for legend 
par(new = TRUE) # this command tells R that we are going to add a new plot ON TOP OF THE OLD ONE
plot(abalone$shell.wt ~ abalone$rings, pch = 2, col = "red", ann = FALSE, axes = FALSE) # we make annotations and axes false on this plot because by default they would overwrite the standard y-axis position on the left and we want this plot to use a second y-axis on the right
axis(4) # draw an axis for the most recent plot on the right side (side 4)
mtext("Shell weight", 4, line = 2) # add text into the margin on the right side (side 4), placed 2 lines beyond the axis line
```

Add lines.
  There are 4 different function commonly used to add lines to graphs: `lines()`, `segments()`, `abline()`, `arrows()`. We'll see all of these eventually, but for now consider `abline()`, which lets us add a straight line with the equation y ~ a + bx, or a horizontal line at y-value, h = y or a vertical line at x-value, v = x.
  
```{r}
#same graph as above
par(mai=c(0.5,0.5,0.5,1)) 
plot(abalone$whole.wt ~ abalone$rings) 
par(new = TRUE) 
plot(abalone$shell.wt ~ abalone$rings, pch = 2, col = "red", ann = FALSE, axes = FALSE) 
axis(4) 
mtext("Shell weight", 4, line = 2) 
abline(v = mean(abalone$rings), col = "blue", lwd = 4) # add vertical line that meets x-axis at the mean value for rings, is a blue colour and is 4 pts wide.
```


####Interactive Plotting Functions

The function `identify()` is a useful interactive plotting function that allows you to use your mouse to identify the data.frame row for any point on a plot.
** note that this will not work wihin the notebook. You will need to copy and paste the 2 lines below into the console to see interactive feature.**
```{r}
plot(abalone$whole.wt ~ abalone$rings) # first plot data
identify(abalone$rings, abalone$whole.wt) # then give same data to indentify function
```


### GGPlot2 Package

Below are the code to replicate the basic high level plot functions we did above for base graphics in R, using the ggplot function found in the ggplot2 package instead.

Plot histogram
```{r}
library(ggplot2)
```
```{r}
ggplot(abalone, aes(x = length)) + geom_histogram()
```

Plot Density Curve
```{r}
ggplot(abalone, aes(x=length)) + stat_density()
```
One of the nice features of ggplot is that we can save our graph as an object and then more readily try out different graphing styles (geoms).
```{r}
gr1 <- ggplot(abalone, aes(x=length)) # save plot to object gr1
gr1 + geom_histogram() # try histogram 
gr1 + stat_density()  # try density curve
```
Scatter Plot
```{r}
graphics.off() # this resets all your graphics parameters and it is a good idea to run this before running each new graph, especially if you have made a number of parameter changes
ggplot(abalone, aes(x = rings, y = whole.wt)) + geom_point() # geom_point() gives us a scatter plot
```

Boxplot
```{r}
p <- ggplot(abalone, (aes(x = as.factor(rings), y= length))) # because we want to use rings as a categorical variable, we need to re-class it as a factor (currently it is in data.frame as an integer)
p + geom_boxplot()
```
Force scatter plot
```{r}
p + geom_point() #forcting a scatter plot with a factor variable requires only that we invoke a different geom object when using ggplot
```










Add a new chunk by clicking the *Insert Chunk* button on the toolbar or by pressing *Cmd+Option+I*.

When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the *Preview* button or press *Cmd+Shift+K* to preview the HTML file).
