-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNYCASAMetro.Rmd
432 lines (303 loc) · 10.5 KB
/
NYCASAMetro.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
---
title: "Panel plots in R"
author: "Joyce Robbins"
output:
slidy_presentation:
fig_height: 4
fig_width: 6
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(warning = FALSE, message = FALSE, cache = TRUE,
fig.align = 'center')
```
## Agenda
* Basic faceting in `ggplot2`
* When to free scales
* Getting data in the right form
* Plotting one variable per panel
* Design decisions with multiple variables
* Scatterplot matrices
Slides and code: https://www.github.com/jtr13/panelplots
## Without faceting
```{r}
library(tidyverse)
g <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
g
```
## Facet on one variable with `facet_wrap()`
facet "on" Species
```{r}
g + facet_wrap(~Species)
```
## Faceting in ggplot2
Each panel represents one categorical group / levels of a factor (type can be factor or character or integer)
```{r}
glimpse(iris)
```
## Change the layout with `nrow, ncol`
```{r}
g + facet_wrap(~Species, ncol = 1)
```
## Add regression lines
```{r}
g + geom_smooth(method = "lm", se = FALSE) + facet_wrap(~Species)
```
## Facet on two (categorical) variables with `facet_grid()`
```{r}
ggplot(mtcars, aes(hp,mpg)) + geom_point() + facet_grid(cyl~gear)
```
## Label variables (in addition to factor levels)
```{r}
ggplot(mtcars, aes(hp, mpg)) + geom_point() + facet_grid(cyl~gear, labeller = label_both)
```
## Cleveland dot plots
Note that y-axis is discrete
```{r}
g <- mtcars %>% rownames_to_column("car") %>%
ggplot(aes(mpg, reorder(car, mpg))) + geom_point(color = "blue") + theme_bw() +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()) + ylab("")
g
```
## Facet by gear
```{r}
g + facet_grid(gear ~ .,
labeller = label_both)
```
## "Free" the y scale with `scales = "free_y"`
```{r}
g + facet_grid(gear ~ ., labeller = label_both, scales = "free_y")
```
## Change panel heights with `space = "free_y"`
```{r}
g + facet_grid(gear ~ ., labeller = label_both, scales = "free_y",
space = "free_y")
```
## In general, do not "free" numerical scales
```{r}
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() + facet_wrap(~Species, scales = "free")
```
incorrect
## In general, do not "free" numerical scales
```{r}
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() + facet_wrap(~Species)
```
correct
## Data must be in the right form to facet
One column of categorical data = one faceting direction
```{r}
library(ggplot2movies)
str(movies)
```
## Facet on `Action` column
```{r}
movies %>% filter(!is.na(budget)) %>% sample_n(1000) %>%
ggplot(aes(budget, length)) + geom_point() +
facet_wrap(~Action)
```
## Transform data
```{r}
mymovies <- movies %>%
select(title, length, budget, year, mpaa, Action:Short) %>%
gather(key = "genre", value, Action:Short) %>%
filter(value == 1) %>%
select(-value)
head(mymovies)
```
## Facet on `genre`
```{r}
lengthorder <- mymovies %>% group_by(genre) %>% summarize(meanlength = mean(length)) %>% arrange(desc(meanlength))
mymovies %>% filter(!is.na(budget)) %>%
sample_n(1000) %>%
ggplot(aes(budget/1000000, length)) + geom_point() +
facet_wrap(~factor(genre, levels = lengthorder$genre)) + xlab("budget (in millions)") +
geom_hline(data = lengthorder, aes(yintercept = meanlength), color = "red") +
ggtitle ("Length vs. Budget", subtitle = "Red line indicates mean length")
```
## Use facets to look at distributions of numeric variables
```{r}
newmovies <- movies %>% select(mpaa, year:votes) %>% gather(key = "variable", value, -mpaa) %>%
filter(!is.na(value))
newmovies %>% sample_n(6)
```
##
```{r}
ggplot(newmovies, aes(value)) + geom_histogram(fill = "cornflowerblue") + facet_wrap(~variable, scales = "free")
```
variables become levels of the new "variable" column
## Facet on `mpaa` and `variable`
```{r}
ggplot(newmovies, aes(value)) + geom_histogram(fill = "cornflowerblue") + facet_grid(mpaa~variable, scales = "free") + theme_bw()
```
## One common scale
Same technique: variables become levels of a new "variable" column
```{r, echo = FALSE}
byyear <- movies %>% select(title:votes) %>%
mutate(budget_millions = budget/1000000) %>%
select(-budget) %>%
gather(key = "variable", value, -title, -year) %>%
group_by(year, variable) %>%
summarize(mean = mean(value, na.rm = T))
ggplot(byyear, aes(year, mean)) + geom_line() + facet_wrap(~variable, ncol = 1,
scales = "free_y") +
ggthemes::theme_economist()
```
## Data
```{r, eval = FALSE}
byyear <- movies %>% select(title:votes) %>%
mutate(budget_millions = budget/1000000) %>%
select(-budget) %>%
gather(key = "variable", value, -title, -year) %>%
group_by(year, variable) %>%
summarize(mean = mean(value, na.rm = T))
```
```{r}
glimpse(byyear)
```
```{r, eval = FALSE}
ggplot(byyear, aes(year, mean)) + geom_line() +
facet_wrap(~variable, ncol = 1, scales = "free_y") + ggthemes::theme_economist()
```
## Convert numerical to categorical variables
```{r}
mymovies <- mymovies %>% filter(length <= 180) %>%
mutate(decade = factor(round(year/10)*10))
ggplot(mymovies, aes(length)) + geom_histogram(fill = "cornflowerblue") +
facet_wrap(~decade)
```
## ggridges
```{r}
library(ggridges)
ggplot(mymovies, aes(x=length, y=fct_rev(decade))) +
geom_density_ridges(scale = 1.5, color = "blue", fill = "blue", alpha = .4) +
xlab("Length (in minutes)") +
ylab("") +
theme_ridges()
```
## Design choices with multiple variables
x-axis, y-axis, row facets, column facets
color, size, shape
## Think about continuous vs. categorical variables
```{r, eval = FALSE, echo = FALSE}
topmethods <- c("E-mail", "Telephone", "Sales visit", "Web")
topretailer <- c("Department Store", "Sports Store", "Outdoors Shop")
toplines <- c("Camping Equipment", "Mountaineering Equipment",
"Golf Equipment", "Personal Accessories")
sales <- read_csv("sales.csv") %>%
select(`Order method type`:`Product line`, Revenue, Date) %>%
mutate(Revenue = Revenue / 1000000) %>%
filter(`Order method type` %in% topmethods,
`Retailer type` %in% topretailer,
`Product line` %in% toplines) %>%
mutate(`Retailer type` = str_remove_all(`Retailer type`, "( Store| Shop)")) %>%
mutate(`Product line` = str_remove_all(`Product line`, "( Equipment| Accessories)"))
write_csv(sales, "sales2.csv")
```
```{r}
sales <- read_csv("sales2.csv")
glimpse(sales)
```
## Start with one dimension
```{r}
sales %>% group_by(Date) %>% summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev)) + geom_line() + ylab("millions $") + ggtitle("Revenue")
```
## Consider one variable at a time
```{r}
sales %>% group_by(Date, `Product line`) %>%
summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev, color = fct_reorder2(`Product line`, Date, SumRev))) + geom_line() +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") + ylab("millions $") + ggtitle("Revenue by Product line") +
labs(color = "Product line")
```
## Consider one variable at a time
```{r}
sales %>% group_by(Date, `Order method type`) %>%
summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev, color = fct_reorder2(`Order method type`, Date, SumRev))) + geom_line() +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") + ylab("millions $") + ggtitle("Revenue by Order method type") +
labs(color = "Order method type")
```
## Consider one variable at a time
```{r}
sales %>% group_by(Date, `Retailer type`) %>%
summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev, color = fct_reorder2(`Retailer type`, Date, SumRev))) + geom_line() +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") + ylab("millions $") + ggtitle("Revenue by Retailer type") +
labs(color = "Retailer type")
```
## Add faceting (one dimension)
Reorder factor levels
```{r}
sales <- sales %>%
mutate(`Product line` = reorder(`Product line`, Revenue, function(x) sum(x)*-1),
`Order method type` = reorder(`Order method type`, Revenue, function(x) sum(x)*-1),
`Retailer type` = reorder(`Retailer type`, Revenue, function(x) sum(x)*-1))
```
## Add faceting (one dimension)
```{r}
sales %>% group_by(Date, `Product line`, `Order method type`) %>%
summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev, color = `Order method type`)) + geom_line() +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") +
facet_wrap(~`Product line`) + ylab("millions $") +
theme(legend.position = "bottom") +
ggtitle("Revenue, faceted on product line")
```
## Faceting (two dimensions)
```{r}
sales %>% group_by(Date, `Product line`, `Retailer type`, `Order method type`) %>%
summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev, color = `Product line`)) + geom_line() +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") +
facet_grid(`Retailer type`~`Order method type`) +
theme_bw() + theme(legend.position = "bottom") +
ggtitle("Revenue, faceted on Order method and Retailer type")
```
## Experiment
```{r}
sales %>% group_by(Date, `Product line`, `Retailer type`, `Order method type`) %>%
summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev, color = `Retailer type`)) + geom_line() +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") +
facet_grid(`Product line`~`Order method type`) +
theme_bw() + theme(legend.position = "bottom") +
ggtitle("Revenue, faceted on Order method and Product line")
```
## Experiment
```{r}
sales %>% group_by(Date, `Product line`, `Retailer type`, `Order method type`) %>%
summarize(SumRev = sum(Revenue)) %>%
ggplot(aes(Date, SumRev, color = `Order method type`)) + geom_line() +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") +
facet_grid(`Product line`~`Retailer type`) +
theme_bw() + theme(legend.position = "bottom") +
ggtitle("Revenue, faceted on Retailer type and Product line")
```
## Scatterplot matrices
Can't create with faceting in `ggplot2`
Options:
`plot()`
`lattice::splom()`
`GGally::ggpairs()`
## Scatterplot matrices
```{r, fig.width = 5, fig.height = 5}
plot(iris)
```
## Scatterplot matrices
```{r, fig.width = 5, fig.height = 5}
lattice::splom(iris)
```
## Scatterplot matrices
```{r, fig.width = 5, fig.height = 5}
lattice::splom(iris[,1:4], group = iris$Species,
par.settings = list(superpose.symbol = list(pch = 16, cex = .5)),
axis.text.cex = .5, axis.text.col = "grey50",
axis.line.tck = .5, auto.key = TRUE)
```
## Scatterplot matrices
```{r, fig.width = 5, fig.height = 5}
GGally::ggpairs(iris, mapping = ggplot2::aes(color = Species))
```