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.html
228 lines (203 loc) · 12.5 KB
/
block016_secrets-happy-graphing.html
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<title>Secrets of a happy graphing life</title>
<script src="libs/jquery-1.11.0/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="libs/bootstrap-2.3.2/css/united.min.css" rel="stylesheet" />
<link href="libs/bootstrap-2.3.2/css/bootstrap-responsive.min.css" rel="stylesheet" />
<script src="libs/bootstrap-2.3.2/js/bootstrap.min.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<link rel="stylesheet"
href="libs/highlight/default.css"
type="text/css" />
<script src="libs/highlight/highlight.js"></script>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs && document.readyState && document.readyState === "complete") {
window.setTimeout(function() {
hljs.initHighlighting();
}, 0);
}
</script>
<link rel="stylesheet" href="libs/local/nav.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
</style>
<div class="container-fluid main-container">
<header>
<div class="nav">
<a class="nav-logo" href="index.html">
<img src="static/img/stat545-logo-s.png" width="70px" height="70px"/>
</a>
<ul>
<li class="home"><a href="index.html">Home</a></li>
<li class="faq"><a href="faq.html">FAQ</a></li>
<li class="syllabus"><a href="syllabus.html">Syllabus</a></li>
<li class="topics"><a href="topics.html">Topics</a></li>
<li class="people"><a href="people.html">People</a></li>
</ul>
</div>
</header>
<div id="header">
<h1 class="title">Secrets of a happy graphing life</h1>
</div>
<div id="TOC">
<ul>
<li><a href="#hidden-data-wrangling-problems">Hidden data wrangling problems</a></li>
<li><a href="#keep-stuff-in-data.frames">Keep stuff in data.frames</a><ul>
<li><a href="#explicit-data.frame-creation-via-dplyrdata_frame">Explicit data.frame creation via <code>dplyr::data_frame()</code></a></li>
<li><a href="#sidebar-with">Sidebar: <code>with()</code></a></li>
</ul></li>
<li><a href="#tidying-and-reshaping">Tidying and reshaping</a></li>
<li><a href="#factor-management">Factor management</a></li>
<li><a href="#worked-example">Worked example</a><ul>
<li><a href="#reshape-your-data">Reshape your data</a></li>
<li><a href="#iterate-over-the-variables-via-facetting">Iterate over the variables via facetting</a></li>
<li><a href="#recap">Recap</a></li>
</ul></li>
</ul>
</div>
<div id="hidden-data-wrangling-problems" class="section level3">
<h3>Hidden data wrangling problems</h3>
<p>If you are struggling to make a figure, don’t assume it’s a problem between you and <code>ggplot2</code>. Stop and ask yourself which of these rules you are breaking:</p>
<ul>
<li>Keep stuff in data.frames</li>
<li>Keep your data.frames <em>tidy</em>; be willing to reshape your data often</li>
<li>Use factors and be the boss of them</li>
</ul>
<p>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.</p>
</div>
<div id="keep-stuff-in-data.frames" class="section level3">
<h3>Keep stuff in data.frames</h3>
<p>I see a fair amount of student code where variables are <em>copied out</em> of a data.frame, to exist as stand-alone objects in the workspace.</p>
<pre class="r"><code>gDat <- read.delim("gapminderDataFiveYear.tsv")
life_exp <- gDat$lifeExp
year <- gDat$year</code></pre>
<p>Problem is, <code>ggplot2</code> has an incredibly strong preference for variables in data.frames; it is virtually a requirement for the main data.frame underpinning a plot.</p>
<pre class="r"><code>library(ggplot2)
ggplot(aes(x = year, y = life_exp)) + geom_jitter()</code></pre>
<pre><code>## Error: ggplot2 doesn't know how to deal with data of class uneval</code></pre>
<p>Why not just leave the variables in place and pass the hosting data.frame to the <code>data =</code> argument?</p>
<pre class="r"><code>ggplot(data = gDat, aes(x = year, y = life_exp)) + geom_jitter()</code></pre>
<p><img src="block016_secrets-happy-graphing_files/figure-html/data-in-situ.png" /></p>
<p>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.”</p>
<p>Don’t write-off <code>ggplot2</code> as a highly opinionated outlier! In fact, keeping data in data.frames and computing and visualizing it <em>in situ</em> are widely regarded as best practices. The option to pass a data frame via <code>data =</code> is a common feature of many high-use R functions, e.g. <code>lm()</code>, <code>aggregate()</code>, <code>plot()</code>, and <code>t.test()</code>, so make this your default <em>modus operandi</em>.</p>
<div id="explicit-data.frame-creation-via-dplyrdata_frame" class="section level4">
<h4>Explicit data.frame creation via <code>dplyr::data_frame()</code></h4>
<p>If your data is already lying around and it’s <strong>not</strong> 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 <code>data_frame()</code> function in <code>dplyr</code> is an improved version of the built-in <code>data.frame()</code>, 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.</p>
<pre class="r"><code>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))</code></pre>
<p><img src="block016_secrets-happy-graphing_files/figure-html/data_frame-love.png" /></p>
<p>Together with <code>dplyr::mutate()</code>, 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.</p>
</div>
<div id="sidebar-with" class="section level4">
<h4>Sidebar: <code>with()</code></h4>
<p>Sadly, not all functions offer a <code>data =</code> argument. Take <code>cor()</code>, for example, which computes correlation. This does <strong>not</strong> work:</p>
<pre class="r"><code>cor(year, lifeExp, data = gDat)</code></pre>
<pre><code>## Error: unused argument (data = gDat)</code></pre>
<p>Sure, you can always just repeat the data.frame name like so:</p>
<pre class="r"><code>cor(gDat$year, gDat$lifeExp)</code></pre>
<pre><code>## [1] 0.4356112</code></pre>
<p>but people hate typing. I suspect subconscious dread of repeatedly typing <code>gDat</code> is what motivates those who copy variables into stand-alone objects in the workspace.</p>
<p>The <code>with()</code> 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.</p>
<pre class="r"><code>with(gDat,
cor(year, lifeExp))</code></pre>
<pre><code>## [1] 0.4356112</code></pre>
</div>
</div>
<div id="tidying-and-reshaping" class="section level3">
<h3>Tidying and reshaping</h3>
<p><em>This is an entire topic – multiple topics, in fact – covered elsewhere.</em></p>
<p>See <a href="http://stat545-ubc.github.io/bit002_tidying-lotr-data.html">the lesson contributed to Data Carpentry</a> for info on tidy data.</p>
<p><em>There’s a block under development on other reshaping tasks.</em></p>
</div>
<div id="factor-management" class="section level3">
<h3>Factor management</h3>
<p><em>This is an entire topic, covered elsewhere.</em></p>
<p>See <a href="block014_factors.html">Be the boss of your factors</a> 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.</p>
<!-- 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. -->
</div>
<div id="worked-example" class="section level3">
<h3>Worked example</h3>
<p>Inspired by this question from a student when we first started using <code>ggplot2</code>: How can I focus in on country, Japan for example, and plot all the quantitative variables against year?</p>
<p>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.</p>
<div id="reshape-your-data" class="section level4">
<h4>Reshape your data</h4>
<p>We filter the Gapminder data and keep only Japan. Then we <em>gather</em> up the variables <code>pop</code>, <code>lifeExp</code>, and <code>gdpPercap</code> into a single <code>value</code> variable, with a companion variable <code>key</code>.</p>
<pre class="r"><code>library(tidyr)
japan_dat <- gDat %>%
filter(country == "Japan")
japan_tidy <- japan_dat %>%
gather(key = var, value = value, pop, lifeExp, gdpPercap)
dim(japan_dat)</code></pre>
<pre><code>## [1] 12 6</code></pre>
<pre class="r"><code>dim(japan_tidy)</code></pre>
<pre><code>## [1] 36 5</code></pre>
<p>The filtered <code>japan_dat</code> has 12 rows. Since we are gathering or stacking three variables in <code>japan_tidy</code>, it makes sense to see three times as many rows, namely 36 in the reshaped result.</p>
</div>
<div id="iterate-over-the-variables-via-facetting" class="section level4">
<h4>Iterate over the variables via facetting</h4>
<p>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.</p>
<pre class="r"><code>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))</code></pre>
<p><img src="block016_secrets-happy-graphing_files/figure-html/japan.png" /></p>
</div>
<div id="recap" class="section level4">
<h4>Recap</h4>
<p>Here’s the minimal code to produce our Japan example.</p>
<pre class="r"><code>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))</code></pre>
<p>This snippet demonstrates the payoffs from the rules we laid out at the start:</p>
<ul>
<li>We isolate the Japan data into its own <strong>data.frame</strong>.</li>
<li>We <strong>reshape</strong> the data. It’s a classic case of <strong>tidying</strong>. We gather three columns into one, because we want to depict them via position along the y-axis in the plot.</li>
<li>We use a <strong>factor</strong> to distinguish the observations that belong in each mini-plot, which then becomes a simple application of facetting.</li>
</ul>
</div>
</div>
<div class="footer">
This work is licensed under the <a href="http://creativecommons.org/licenses/by-nc/3.0/">CC BY-NC 3.0 Creative Commons License</a>.
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
$(document).ready(function () {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>