forked from STAT545-UBC/STAT545-UBC-original-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock016_secrets-happy-graphing.rmd
154 lines (106 loc) · 7.05 KB
/
block016_secrets-happy-graphing.rmd
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
---
title: Secrets of a happy graphing life
output:
html_document:
toc: true
toc_depth: 4
---
```{r setup, include = FALSE, cache = FALSE}
knitr::opts_chunk$set(error = TRUE)
```
### Hidden data wrangling problems
If you are struggling to make a figure, don't assume it's a problem between you and `ggplot2`. Stop and ask yourself which of these rules you are breaking:
* Keep stuff in data.frames
* Keep your data.frames *tidy*; be willing to reshape your data often
* Use factors and be the boss of them
In my experience, the vast majority of graphing agony is due to insufficient data wrangling. Tackle your latent data storage and manipulation problems and your graphing problem often melts away.
### Keep stuff in data.frames
I see a fair amount of student code where variables are *copied out* of a data.frame, to exist as stand-alone objects in the workspace.
```{r}
gDat <- read.delim("gapminderDataFiveYear.tsv")
life_exp <- gDat$lifeExp
year <- gDat$year
```
Problem is, `ggplot2` has an incredibly strong preference for variables in data.frames; it is virtually a requirement for the main data.frame underpinning a plot.
```{r}
library(ggplot2)
ggplot(aes(x = year, y = life_exp)) + geom_jitter()
```
Why not just leave the variables in place and pass the hosting data.frame to the `data =` argument?
```{r data-in-situ}
ggplot(data = gDat, aes(x = year, y = life_exp)) + geom_jitter()
```
What if we wanted to filter the data by country, continent, or year? This is much easier to do safely if all affected variables live together in a data.frame, not as individual objects that can get "out of sync."
Don't write-off `ggplot2` as a highly opinionated outlier! In fact, keeping data in data.frames and computing and visualizing it *in situ* are widely regarded as best practices. The option to pass a data frame via `data =` is a common feature of many high-use R functions, e.g. `lm()`, `aggregate()`, `plot()`, and `t.test()`, so make this your default *modus operandi*.
#### Explicit data.frame creation via `dplyr::data_frame()`
If your data is already lying around and it's __not__ in a data.frame, ask yourself "why not?". Did you create those variables? Maybe you should have created them in a data.frame in the first place! The new `data_frame()` function in `dplyr` is an improved version of the built-in `data.frame()`, which makes it possible to define one variable in terms of another and that won't mangle your imports via coercion. This removes my most common excuses for data.frame procrastination and avoidance.
```{r data_frame-love}
suppressPackageStartupMessages(library(dplyr))
my_dat <-
data_frame(x = 1:5,
y = x ^ 2,
text = c("alpha", "beta", "gamma", "delta", "epsilon"))
ggplot(my_dat, aes(x, y)) + geom_line() + geom_text(aes(label = text))
```
Together with `dplyr::mutate()`, which adds new variables to a data.frame, this gives you the tools to work within data.frames whenever you're handling related variables of the same length.
#### Sidebar: `with()`
Sadly, not all functions offer a `data =` argument. Take `cor()`, for example, which computes correlation. This does __not__ work:
```{r}
cor(year, lifeExp, data = gDat)
```
Sure, you can always just repeat the data.frame name like so:
```{r}
cor(gDat$year, gDat$lifeExp)
```
but people hate typing. I suspect subconscious dread of repeatedly typing `gDat` is what motivates those who copy variables into stand-alone objects in the workspace.
The `with()` function is much better workaround. Provide the data.frame as the first argument. The second argument is an expression that will be evaluated in a special environment. It could be a single command or a multi-line snippet of code. What's special is that you can refer to variables in the data.frame by name.
```{r}
with(gDat,
cor(year, lifeExp))
```
### Tidying and reshaping
*This is an entire topic -- multiple topics, in fact -- covered elsewhere.*
See [the lesson contributed to Data Carpentry](http://stat545-ubc.github.io/bit002_tidying-lotr-data.html) for info on tidy data.
*There's a block under development on other reshaping tasks.*
### Factor management
*This is an entire topic, covered elsewhere.*
See [Be the boss of your factors](block014_factors.html) to learn how to take charge of factor levels and their order and for how to map old levels into new ones. You'll also see demos of the downstream pay-offs, e.g. more effective figures.
<!-- possible example to put here: someone coding male/female as 0/1. Then struggling with, say, the ggplot2 legend or the labelling in t.test output. Solution: just create the darn factor with male vs female! Maybe would work better if factor had three levels and I could use lm output to show much more self-documenting it is with a properly levelled factor. -->
### Worked example
Inspired by this question from a student when we first started using `ggplot2`: How can I focus in on country, Japan for example, and plot all the quantitative variables against year?
Your first instinct might be to filter the Gapminder data for Japan and then loop over the variables, creating separate plots which need to be glued together. And, indeed, this can be done. But in my opinion, the data reshaping route is more "R native" given our current ecosystem, than the loop way.
#### Reshape your data
We filter the Gapminder data and keep only Japan. Then we *gather* up the variables `pop`, `lifeExp`, and `gdpPercap` into a single `value` variable, with a companion variable `key`.
```{r}
library(tidyr)
japan_dat <- gDat %>%
filter(country == "Japan")
japan_tidy <- japan_dat %>%
gather(key = var, value = value, pop, lifeExp, gdpPercap)
dim(japan_dat)
dim(japan_tidy)
```
The filtered `japan_dat` has `r nrow(japan_dat)` rows. Since we are gathering or stacking three variables in `japan_tidy`, it makes sense to see three times as many rows, namely `r nrow(japan_tidy)` in the reshaped result.
#### Iterate over the variables via facetting
Now that we have the data we need in a tidy data.frame, with a proper factor representing the variables we want to "iterate" over, we just have to facet.
```{r japan}
p <- ggplot(japan_tidy, aes(x = year, y = value)) +
facet_wrap(~ var, scales="free_y")
p + geom_point() + geom_line() +
scale_x_continuous(breaks = seq(1950, 2011, 15))
```
#### Recap
Here's the minimal code to produce our Japan example.
```{r eval = FALSE}
japan_tidy <- gDat %>%
filter(country == "Japan") %>%
gather(key = var, value = value, pop, lifeExp, gdpPercap)
ggplot(japan_tidy, aes(x = year, y = value)) +
facet_wrap(~ var, scales="free_y") +
geom_point() + geom_line() +
scale_x_continuous(breaks = seq(1950, 2011, 15))
```
This snippet demonstrates the payoffs from the rules we laid out at the start:
* We isolate the Japan data into its own __data.frame__.
* We __reshape__ the data. It's a classic case of __tidying__. We gather three columns into one, because we want to depict them via position along the y-axis in the plot.
* We use a __factor__ to distinguish the observations that belong in each mini-plot, which then becomes a simple application of facetting.