This repository has been archived by the owner on Sep 18, 2019. It is now read-only.
/
block016_secrets-happy-graphing.html
344 lines (299 loc) · 15 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
<!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.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-68219208-1', 'auto');
ga('send', 'pageview');
</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>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="libs/local/main.css" type="text/css" />
<link rel="stylesheet" href="libs/local/nav.css" type="text/css" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<div class="container-fluid main-container">
<!-- tabsets -->
<script src="libs/navigation-1.1/tabsets.js"></script>
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<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 class="fluid-row" id="header">
<h1 class="title toc-ignore">Secrets of a happy graphing life</h1>
</div>
<div id="TOC">
<ul>
<li><a href="#load-gapminder-and-the-tidyverse">Load gapminder and the tidyverse</a></li>
<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-tibbletibble-and-tribble">Explicit data frame creation via <code>tibble::tibble()</code> and <code>tribble()</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="load-gapminder-and-the-tidyverse" class="section level3">
<h3>Load gapminder and the tidyverse</h3>
<pre class="r"><code>library(gapminder)
library(tidyverse)
#> Loading tidyverse: ggplot2
#> Loading tidyverse: tibble
#> Loading tidyverse: tidyr
#> Loading tidyverse: readr
#> Loading tidyverse: purrr
#> Loading tidyverse: dplyr
#> Conflicts with tidy packages ----------------------------------------------
#> filter(): dplyr, stats
#> lag(): dplyr, stats</code></pre>
</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 ggplot2. 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>life_exp <- gapminder$lifeExp
year <- gapminder$year</code></pre>
<p>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.</p>
<pre class="r"><code>ggplot(aes(x = year, y = life_exp)) + geom_jitter()
#> Error: ggplot2 doesn't know how to deal with data of class uneval</code></pre>
<p><strong>Just leave the variables in place and pass the associated data frame!</strong> This advice applies to base and <code>lattice</code> graphics as well. It is not specific to ggplot2.</p>
<pre class="r"><code>ggplot(data = gapminder, aes(x = year, y = life_exp)) + geom_jitter()</code></pre>
<p><img src="block016_secrets-happy-graphing_files/figure-html/data-in-situ-1.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 ggplot2 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-tibbletibble-and-tribble" class="section level4">
<h4>Explicit data frame creation via <code>tibble::tibble()</code> and <code>tribble()</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 <code>tibble()</code> function 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 which won’t turn character data into factor. If constructing tiny tibbles “by hand”, <code>tribble()</code> can be an even handier function, in which your code will be laid out like the table you are creating. These functions should remove the most common excuses for data frame procrastination and avoidance.</p>
<pre class="r"><code>my_dat <-
tibble(x = 1:5,
y = x ^ 2,
text = c("alpha", "beta", "gamma", "delta", "epsilon"))
## if you're truly "hand coding", tribble() is an alternative
my_dat <- tribble(
~ x, ~ y, ~ text,
1, 1, "alpha",
2, 4, "beta",
3, 9, "gamma",
4, 16, "delta",
5, 25, "epsilon"
)
str(my_dat)
#> Classes 'tbl_df', 'tbl' and 'data.frame': 5 obs. of 3 variables:
#> $ x : num 1 2 3 4 5
#> $ y : num 1 4 9 16 25
#> $ text: chr "alpha" "beta" "gamma" "delta" ...
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-1.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 = gapminder)
#> Error in cor(year, lifeExp, data = gapminder): unused argument (data = gapminder)</code></pre>
<p>Sure, you can always just repeat the data frame name like so:</p>
<pre class="r"><code>cor(gapminder$year, gapminder$lifeExp)
#> [1] 0.4356112</code></pre>
<p>but people hate typing. I suspect subconscious dread of repeatedly typing <code>gapminder</code> is what motivates those who copy variables into stand-alone objects in the workspace.</p>
<p>The <code>with()</code> function is a 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(gapminder,
cor(year, lifeExp))
#> [1] 0.4356112</code></pre>
<p>If you use the <code>magrittr</code> package, another option is to use the <code>%$%</code> operator to expose the variables inside a data frame for further computation:</p>
<pre class="r"><code>library(magrittr)
#>
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#>
#> set_names
#> The following object is masked from 'package:tidyr':
#>
#> extract
gapminder %$%
cor(year, lifeExp)
#> [1] 0.4356112</code></pre>
</div>
</div>
<div id="tidying-and-reshaping" class="section level3">
<h3>Tidying and reshaping</h3>
<p>This is an entire topic covered elsewhere:</p>
<p><a href="https://github.com/jennybc/lotr-tidy#readme">Tidy data using Lord of the Rings</a></p>
</div>
<div id="factor-management" class="section level3">
<h3>Factor management</h3>
<p>This is an entire topic covered elsewhere:</p>
<p><a href="block029_factors.html">Be the boss of your factors</a></p>
</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 ggplot2: 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>japan_dat <- gapminder %>%
filter(country == "Japan")
japan_tidy <- japan_dat %>%
gather(key = var, value = value, pop, lifeExp, gdpPercap)
dim(japan_dat)
#> [1] 12 6
dim(japan_tidy)
#> [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-1.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 <- gapminder %>%
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. 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>
<li>This is an example of expedient data reshaping. I don’t actually believe that <code>gdpPercap</code>, <code>lifeExp</code>, and <code>pop</code> naturally belong together in one variable. But gathering them was by far the easiest way to get this plot.</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>