-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREADME.Rmd
More file actions
427 lines (344 loc) · 13 KB
/
README.Rmd
File metadata and controls
427 lines (344 loc) · 13 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
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
---
output:
github_document:
html_preview: false
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
# plot-recreation
<!-- badges: start -->
<!-- badges: end -->
Re-creating plots to learn cool tricks and practice problem-solving.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
error = TRUE,
fig.path = 'figures/')
```
```{r libs, message=FALSE}
library(cowplot)
library(glue)
library(ggtext)
library(gridtext)
library(here)
library(magick)
library(RColorBrewer)
library(tidyverse)
set.seed(2020)
```
## Exercises
View the plots below and try to write the code that creates them!
There are more exercises here than you can probably get to in the time allotted.
Feel free to jump around and pick ones to work on based on how interested you are in learning how to create the plot.
At the end, we'll each share one solution.
As much as this is an exercise in data viz with R, it's also an exercise in finding solutions in package documentation and general problem-solving.
Google is your friend!
If you get stuck, take a look at the [hints](hints.md) or send Kelly a message in Slack.
- [Exercises](#exercises)
- [Italicize text](#italicize-text)
- [Color axis text](#color-axis-text)
- [Color & bold axis label](#color-bold-axis-label)
- [Assign colors manually](#assign-colors-manually)
- [Image on a plot](#image-on-a-plot)
- [Plot on an image](#plot-on-an-image)
- [Plots in a grid](#plots-in-a-grid)
- [One title for two plots](#one-title-for-two-plots)
- [Inset plots](#inset-plots)
- [Overlaying plots](#overlaying-plots)
- [Multi-panel figure](#multi-panel-figure)
- [Solutions](#solutions)
### Italicize text

Source: [Claus Wilke's talk at rstudio::conf(2020)](https://twitter.com/ClausWilke/status/1222944728443809792)
```{r otu_italics}
otu_data <- tribble(~otu, ~bact, ~value,
1, 'Staphylococceae', -0.5,
2, 'Moraxella', 0.5,
3, 'Streptococcus', 2,
4, 'Acinetobacter', 3.0
) %>% mutate(name = glue("*{bact}* (OTU {otu})"))
otu_data %>%
ggplot(aes(XXXXXX, XXXXXX)) +
geom_XXXXXX() +
XXXXXX() +
theme(axis.text.y = XXXXXX)
```
### Color axis text

Source: [Claus Wilke's talk at rstudio::conf(2020)](https://twitter.com/ClausWilke/status/1222944728443809792)
```{r otu_color}
# make some fake data
otu_data <- tribble(~otu, ~bact, ~value,
1, 'Staphylococceae', -0.5,
2, 'Moraxella', 0.5,
3, 'Streptococcus', 2,
4, 'Acinetobacter', 3.0
) %>%
mutate(color = brewer.pal(4, "Dark2"),
name = glue("<i style='color:{color}'>{bact}</i> (OTU {otu})")
)
# plot it
otu_data %>%
ggplot(aes(name, value, fill=color)) +
geom_XXXXXX() +
scale_XXXXXX_identity() +
XXXXXX_flip() +
XXXXXX(axis.text.y = XXXXXX)
```
### Color & bold axis label

Inspiration: fig. 2C from Jay's recent journal club paper: [Zhai et al 2018 Nature Med](https://www.nature.com/articles/s41591-019-0709-7/figures/2)
```{r candidemia_color}
# make some fake data
time_data <-tibble(time = seq(0,5,0.1),
yes = sin(time * 0.8) + 0.8,
no = sin(time * -0.5) + 1
) %>% pivot_longer(-time, names_to = "infected", values_to = "value")
head(time_data)
# plot it
time_data %>% ggplot(aes(x = XXXXXX, y = XXXXXX, color = infected)) +
geom_XXXXXX() +
ylab("<b style='color:#00BFC4'>Candidemia</b> vs. <b style='color:#F8766D'>no Candidemia</b> ITS1 diversity") +
theme_XXXXXX() +
theme(legend.position = XXXXXX,
axis.title.y = XXXXXX)
```
### Assign colors manually

Adapted from: https://github.com/SchlossLab/compositional_data_analysis
```{r color_manual}
palette = brewer.pal(n = 4, name = "Paired")
colors = c(A = palette[[2]],
B = palette[[3]])
otu_table <- tibble(
sample = c("1", "2", "3", "1", "2", "3"),
otu = c("A", "A", "A", "B", "B", "B"),
abun = c(5, 15, 6, 15, 5, 2)
) %>% mutate(color = colors[otu])
# plot total counts (aboslute abundace)
otu_table %>%
ggplot(aes(x = sample, y = XXXXXX, fill = XXXXXX)) +
geom_XXXXXX() +
scale_XXXXXX_XXXXXX() +
XXXXXX("Total bacteria") +
theme_classic()
```
### Image on a plot

Adapted from: https://github.com/SchlossLab/compositional_data_analysis
```{r img_on_plot}
otu_table <- tibble(
sample = c("1", "2", "3", "1", "2", "3"),
otu = c("A", "A", "A", "B", "B", "B"),
abun = c(5, 15, 6, 15, 5, 2)
)
# from https://github.com/mothur/logo
logo_file <- here("figures", "mothur_RGB.png")
# plot total counts (aboslute abundace)
plot_total <- otu_table %>%
ggplot(aes(x = XXXXXX, y = XXXXXX, fill = XXXXXX)) +
geom_XXXXXX() +
XXXXXX("Total bacteria") +
theme_classic()
ggXXXX() +
draw_XXXXXX(plot_total) +
draw_XXXXXX(logo_file, x = 1, y = 1,
hjust = 1.2, vjust = 1.2,
width = 0.3, height = 0.3)
```
### Plot on an image
_With great power, comes great responsibility. Use at your own risk!_

Adapted from: https://wilkelab.org/cowplot/articles/drawing_with_on_plots.html#combining-plots-and-images
```{r plot_on_img}
rides <- read_csv('https://raw.githubusercontent.com/kelly-sovacool/strava/master/data/processed/activities.csv', col_types = cols()) %>%
filter(distance_mi > 1, as.character(type) == 'Ride', year >= 2019) %>%
select(distance_mi, start_date)
# source https://www.pinclipart.com/picdir/big/196-1969309_free-bicycle-bike-cartoon-no-background-clipart.png
bike_img <- here('figures', 'bike.png') %>%
image_read() %>%
image_colorize(70, "white")
# make the plot
rides_plot <- rides %>%
ggplot(aes(XXXXXX, XXXXXX)) +
geom_point(color='blue', alpha=0.8, size=2) +
theme_XXXXXX()
XXXXXX() +
draw_XXXXXX(bike_img) +
draw_XXXXXX(rides_plot)
```
### Plots in a grid

Adapted from: https://github.com/SchlossLab/OptiFitAnalysis/tree/master/exploratory/2020#performance-as-measured-by-runtime
```{r plot_grid}
benchmarks_fit <-read_tsv('https://raw.githubusercontent.com/SchlossLab/OptiFitAnalysis/master/subworkflows/2_fit_reference_db/results/benchmarks.tsv?token=AEHR6TPPUNNM245DZ7TUP2C7ADK5E', col_types = cols())
benchmarks_clust <- read_tsv('https://raw.githubusercontent.com/SchlossLab/OptiFitAnalysis/master/subworkflows/1_prep_samples/results/benchmarks.tsv?token=AEHR6TNCIGRVN3B5GEVRVNC7ADLAS', col_types = cols())
plot_box_time <- function(df) {
df %>%
group_by(dataset, method) %>%
ggplot(aes(x = method, y = s, color = dataset)) +
geom_XXXXXX() +
scale_XXXXXX_XXXXXX() +
facet_XXXXXX("ref") +
ylim(0,2100) +
labs(y = 'seconds') +
theme_XXXXXX() +
XXXXXX(axis.title.x = element_blank())
}
time_plot_fit <- benchmarks_fit %>%
plot_box_time() +
XXXXXX(axis.text.y = XXXXXX(),
axis.title.y = XXXXXX())
time_plot_clust <- benchmarks_clust %>%
plot_box_time() +
theme(legend.position = XXXXXX)
plot_XXXXXX(time_plot_clust, time_plot_fit, XXXXXX = "h", rel_widths = c(1,3))
```
### One title for two plots

Adapted from: https://wilkelab.org/cowplot/articles/plot_grid.html#joint-plot-titles
```{r one_title_grid}
mph_per_kph <- 0.621371
rides <- read_csv('https://raw.githubusercontent.com/kelly-sovacool/strava/master/data/processed/activities.csv', col_types = cols()) %>%
filter(distance_mi > 1, as.character(type) == 'Ride') %>%
mutate(average_speed_mph = average_speed * mph_per_kph) %>%
select(distance_mi, average_speed_mph, moving_time_hrs, start_date)
# make a plot grid consisting of two panels
p1 <- ggplot(rides, aes(x = XXXXXX, y = distance_mi)) +
geom_XXXXXX(colour = "blue") +
theme_XXXXXX(12) +
XXXXXX_grid(minor = 'none')
p2 <- ggplot(rides, aes(x = moving_time_hrs, y = XXXXXX)) +
geom_XXXXXX(colour = "green") +
theme_XXXXXX(12) +
background_XXXXXX(minor = 'none') +
theme(axis.title.y = element_XXXXXX())
plot_row <- plot_XXXXXX(p1, p2)
# now add the title
title <- ggXXXX() +
draw_XXXXXX(
"Distance travelled with average speed and time spent moving",
fontface = 'bold',
x = 0,
hjust = 0
) +
XXXXXX(
# add margin on the left of the drawing canvas,
# so title is aligned with left edge of first plot
plot.margin = margin(0, 0, 0, 7)
)
plot_XXXXXX(XXXXXX, plot_row, ncol = XXXXXX,
# rel_heights values control vertical title margins
rel_heights = c(0.1, 1)
)
```
### Inset plots

Adapted from: https://wilkelab.org/cowplot/articles/drawing_with_on_plots.html#making-inset-plots
```{r inset}
rides <- read_csv('https://raw.githubusercontent.com/kelly-sovacool/strava/master/data/processed/activities.csv', col_types = cols()) %>%
filter(distance_mi > 1, as.character(type) == 'Ride') %>%
select(distance_mi, start_date, year)
plot_point <- rides %>% ggplot(aes(start_date, XXXXXX)) +
XXXXXX(color='red') +
theme_minimal_grid(12)
inset <- rides %>%
group_by(year) %>%
summarize(sum_distance_mi=sum(distance_mi)) %>%
ggplot(aes(XXXXXX, sum_distance_mi)) +
geom_bar(stat = "Identity", XXXXXX = "skyblue2", alpha = 0.7) +
labs(y='Total Distance (mi)') +
XXXXXX_XXXXXX_continuous(expand = expansion(mult = c(0, 0.05))) +
theme_XXXXXX_hgrid(11)
ggdraw(plot_point + theme_XXXXXX_open(12)) +
draw_XXXXXX(inset, x = 0.1, y = .45, width = .5, height = .5) +
draw_XXXXXX_XXXXXX(
c("A", "B"),
c(0, 0.1),
c(1, 0.95),
size = 12
)
```
### Overlaying plots

Adapted from: https://wilkelab.org/cowplot/articles/aligning_plots.html
```{r overlay}
# make up some non-sensical data
alpha_data <- tibble(sample = as.factor(1:10),
otu_count = runif(10, min = 0, max = 100),
alpha_div = rnorm(10, mean = 2, sd = 0.5)
)
plot_col <- alpha_data %>%
ggplot(aes(sample, otu_count)) +
XXXXXX_col(fill = "#6297E770") +
XXXXXX_XXXXXX_continuous(expand = expansion(mult = c(0, 0.05)),
position = "right") +
scale_x_discrete() +
XXXXXX_minimal_hgrid(11, rel_small = 1) +
XXXXXX(
panel.grid.major = element_XXXXXX(color = "#6297E770"),
axis.line.x = element_XXXXXX(),
axis.text.x = element_XXXXXX(),
axis.title.x = element_XXXXXX(),
axis.ticks = element_XXXXXX(),
axis.ticks.length = grid::unit(0, "pt"),
axis.text.y = element_XXXXXX(color = "#6297E7"),
axis.title.y = element_XXXXXX(color = "#6297E7")
)
plot_point <- alpha_data %>%
ggplot(aes(sample, alpha_div)) +
XXXXXX_XXXXXX(size = 3, color = "#D5442D") +
XXXXXX_XXXXXX_continuous(limits = c(0, 4.5)) +
theme_half_open(11, rel_small = 1) +
scale_XXXXXX_discrete() +
theme(
axis.ticks.y = element_XXXXXX(color = "#BB2D05"),
axis.text.y = element_XXXXXX(color = "#BB2D05"),
axis.title.y = element_XXXXXX(color = "#BB2D05"),
axis.line.y = element_XXXXXX(color = "#BB2D05")
)
aligned_plots <- XXXXXX_plots(plot_col, plot_point, align="hv", axis="tblr")
overlaid_plots <- XXXXXX(aligned_plots[[1]]) +
XXXXXX_plot(aligned_plots[[2]])
overlaid_plots
```
### Multi-panel figure

Source: https://wilkelab.org/cowplot/articles/shared_legends.html
```{r multi-panel}
# plot 1
p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
geom_XXXXXX() +
stat_smooth(method = "lm") +
facet_XXXXXX(. ~ Species) +
theme_half_open(12) +
background_grid(major = 'y', minor = "none") +
panel_border() +
XXXXXX(legend.position = "none")
# plot 2
p2 <- ggplot(iris, aes(Sepal.Length, fill = Species)) +
XXXXXX_density(alpha = .7) +
scale_XXXXXX_XXXXXX(expand = expansion(mult = c(0, 0.05))) +
theme_XXXXXX_open(12) +
XXXXXX(legend.justification = "top")
p2a <- p2 + XXXXXX(legend.position = "none")
# plot 3
p3 <- ggplot(iris, aes(Sepal.Width, fill = Species)) +
geom_density(alpha = .7) +
XXXXXX_XXXXXX_continuous(expand = c(0, 0)) +
theme_half_XXXXXX(12) +
XXXXXX(legend.position = "none")
legend <- XXXXXX_XXXXXX(p2)
# align all plots vertically
plots <- XXXXXX_XXXXXX(p1, p2a, p3, align = 'v', axis = 'l')
# put together the bottom row and then everything
bottom_row <- plot_XXXXXX(
plots[[2]], plots[[3]], legend,
labels = c("B", "C"),
rel_widths = c(1, 1, .3),
nrow = 1
)
plot_XXXXXX(plots[[1]], bottom_row, labels = c("A"), ncol = 1)
```
## Solutions
A link to the source or inspiration is given under each code chunk.
See the [key](https://github.com/SchlossLab/plot-recreation/tree/key) branch for the exact solutions.
Many of these are taken directly from another source, in some cases with slight modifications. The original creators' copyrights still apply; all are OSI-approved licenses.