-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathggplot2.Rmd
More file actions
197 lines (145 loc) · 8.75 KB
/
Copy pathggplot2.Rmd
File metadata and controls
197 lines (145 loc) · 8.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
---
title: "HTLTC-R: Plotting with ggplot2"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, collapse = TRUE)
library(tidyverse)
library(here)
library(htltcR)
```
```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.width = 7, fig.height = 5)
```
### Using this document
* Code blocks and R code have a grey background (note, code nested in the text is not highlighted in the pdf version of this document but is a different font).
* \# indicates a comment, and anything after a comment will not be evaluated in R
* The comments beginning with \#\# under the code in the grey code boxes are the output from the code directly above; any comments added by us will start with a single \#
* While you can copy and paste code into R, you will learn faster if you type out the commands yourself.
* Read through the document after class. This is meant to be a reference, and ideally, you should be able to understand every line of code. If there is something you do not understand please email us with questions or ask in the following class (you're probably not the only one with the same question!).
### Goals
1. Understand the basics of the ggplot command
2. Be able to make basic plots
### Quick data introduction
We will use the data set `yeast_long`. This data set includes data on the response of budding yeast to mating pheromone over time for following three cell types: wildtype (wt), an sst2 mutant (sst2), and a gpa1 mutant (gpa1). For each mutant there is data on the mean response of a population (avg) as well as the standard deviation of the response (stdev). The data set also includes the time for each data point. The dataset can be loaded into the workspace using `data`. Additionally, we will be using the package tidyverse, which includes ggplot2 package and some other interesting functions.
```{r}
library(tidyverse)
library(htltcR)
data("yeast_long")
```
Now we can take a look at our data.
```{r}
class(yeast_long)
dim(yeast_long)
colnames(yeast_long)
tibble(yeast_long)
```
Using the `class` function we can tell that `yeast` is a data.frame. This means it is a list of vectors each with the same length. Now, let's look closer at the data itself; we see it looks like a table with 4 columns (each with a header) and 51 rows. We can also use the function `tibble` to look at our data.frame, which is very useful to see the format of each one of our columns.
### Basic plotting
Now we have imported some data, so how can we visualize it? R has several different methods for making plots, they are generally refered to as base graphics and ggplot. We will be focusing on the ggplot2 system in these lectures. The gg in ggplot2 stands for the Grammar of Graphics, a system for understanding how graphs are composed and understood, but ggplot2 can still be effectively used without a through understanding of the theoretical underpinings. In this session we will slowly build up a single plot from it's constituent components.
Nearly all plots made using ggplot2 start with the function `ggplot`, this function allows you to specify a data frame that you want to use for your plot. You can also specify what you want to appear on each axis using the `aes` function. In this example, we want:
* Time to appear along the X-axis
* Reading to appear along the Y-axis
```{r}
yeast_plot <- ggplot(yeast_long, aes(x = Time, y = Avg))
yeast_plot
```
Now as you can see, none of our points have appeared on this plot. This is due to the fact that `ggplot` is waiting for us to tell it how we want to represent these data points. In this case, we want to represent the points as a scatterplot, so we will use `geom_point` to display the values.
```{r}
yeast_plot <- ggplot(yeast_long, aes(x = Time, y = Avg)) +
geom_point()
yeast_plot
```
This last example also introduces the system ggplot2 uses for building up plots, namely the `+` sign. Also note that R realizes that the call to `geom_point` is connected to the call to `ggplot`. We will use multiple `+` symbols to build plots often over multiple lines to make it easier to read and understand how the plot is constructed.
You may remember from the data description that we have three types of Yeast Strain represented in this data set (stored in the Strain column), but we haven't told ggplot2 how we want to differentiate the strains. One method to do this is to assign color to differentiate each stain:
```{r}
yeast_plot <- ggplot(yeast_long, aes(x = Time, y = Avg, color = Strain)) +
geom_point()
yeast_plot
```
Notice that the only thing we have changed is adding `color = Strain` to the `ggplot` function call, ggplot2 took care of the rest of the color assignment and producing a legend for us.
`geom_point` is not the only way to represent this data, an alternative would be to use a line graph. This can be accomplished using `geom_line`:
```{r}
yeast_plot <- ggplot(yeast_long, aes(x = Time, y = Avg, color = Strain)) +
geom_line()
yeast_plot
```
We can also choose our own colors.
```{r}
yeast_plot <- ggplot(yeast_long, aes(x = Time, y = Avg, color = Strain)) +
geom_line() +
scale_color_manual(values = c("darkorange","darkgreen","purple"))
yeast_plot
```
Remember the pipe (`%>%`) function? Since ggplot2 is part o tidyverse group of packages, we can also pipe our data into `ggplot` using `%>%`.
```{r}
yeast_plot <- yeast_long %>%
ggplot(aes(x = Time, y = Avg, color = Strain)) +
geom_line() +
scale_color_manual(values = c("darkorange","darkgreen","purple"))
yeast_plot
```
### Adding/Modifying Labels
By default, ggplot2 uses the column headings as the axis labels, but these column headings often don't match exactly the desired axis labels. They can be modified using the labs command. We can also modify the legend title. In our case, the legend refers to the colors.
```{r}
yeast_plot <- yeast_long %>%
ggplot(aes(x = Time, y = Avg, color = Strain)) +
geom_line() +
scale_color_manual(values = c("darkorange","darkgreen","purple")) +
labs(x = "Time (Minutes)",
y = "Mean Pheromone Response",
color = "Yeast Strain")
yeast_plot
```
### Modifying Visual Properties of Plots
The default visual styling of the plots can also be modified using a set of built in themes or built to your own preferences. There are several different themes built into ggplot2 and in general they start with "theme_", here is one example:
```{r}
yeast_plot <- yeast_long %>%
ggplot(aes(x = Time, y = Avg, color = Strain)) +
geom_line() +
scale_color_manual(values = c("darkorange","darkgreen","purple")) +
labs(x = "Time (Minutes)",
y = "Mean Pheromone Response",
color = "Yeast Strain") +
theme_bw()
yeast_plot
```
A full list of the built-in themes is available [here](http://ggplot2.tidyverse.org/reference/ggtheme.html). There are also an extensive list of plot visuals that can be modified using the `theme`.
### Saving Plots
Plots can be saved to a file on your computer using `ggsave`. The most common output formats are PNG, PDF and SVG. PNG files are not easy to edit, but can be easily inserted into powerpoint slides. SVG and PDF can edited using other software including Adobe Illustrator. `ggsave` defaults to saving the last plot made, but can be used to save any plot you have produced. Here's an example:
```{r}
yeast_plot <- yeast_long %>%
ggplot(aes(x = Time, y = Avg, color = Strain)) +
geom_line() +
scale_color_manual(values = c("darkorange","darkgreen","purple")) +
labs(x = "Time (Minutes)",
y = "Mean Pheromone Response",
color = "Yeast Strain") +
theme_bw()
ggsave("yeast_growth.png", yeast_plot)
# This will save the plot in our current working directory,
# to change it, use: "path/to/file/yeast_growth.png"
```
### Exercises
The following questions are to be done for homework. They require the use of the mtcars data set, which is built into R and be accessed throught the mtcars variable. Additional information about the data set can be found with `?mtcars`
1. Make a histogram of the mpg (miles per gallon) column. Hint: check the help on geom_histogram
```{r,eval=FALSE,include=FALSE}
#Possible solution:
ggplot(mtcars, aes(x=mpg)) + geom_histogram()
```
2. Now make the same histogram but with a bin width of 5 and make it your favorite color.
```{r,eval=FALSE,include=FALSE}
#Possible solution:
ggplot(mtcars, aes(x = mpg)) + geom_histogram(binwidth = 5, color = "green")
```
3. Make a bar chart of the number of cars in each of the cylinder classes (identified by the cyl column). Also check out the help for geom_bar.
```{r,eval=FALSE,include=FALSE}
#Possible solution:
ggplot(mtcars, aes(x = cyl, y = mpg)) + geom_bar()
```
4. Make a box plot of the number of cylinders vs the car's total horsepower
```{r,eval=FALSE,include=FALSE}
#Possible solution:
ggplot(mtcars, aes(group = cyl, y = hp, x = cyl)) + geom_boxplot()
```