-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathslides-wcm.Rmd
548 lines (414 loc) · 15 KB
/
slides-wcm.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
---
title: "Swimmer Plots in R using ggplot"
subtitle: "WCM Computing Club - Sept. 6, 2022"
author: Kat Hoffman
output:
xaringan::moon_reader:
lib_dir: libs
css: ["xaringan-themer.css","extra.css"]
nature:
ratio: 16:9
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
seal: false
---
```{r xaringan-themer, include=FALSE, warning=FALSE}
library(xaringanthemer)
library(fontawesome)
library(kableExtra)
style_mono_accent(
base_color = "#1e90ff",
header_font_google = google_font("Josefin Sans"),
text_font_google = google_font("Montserrat", "300", "300i"),
code_font_google = google_font("Fira Mono")
)
```
```{r, include = F}
# This is the recommended set up for flipbooks
# you might think about setting cache to TRUE as you gain practice --- building flipbooks from scratch can be time consuming
knitr::opts_chunk$set(fig.width = 9, message = FALSE, warning = FALSE, comment = "", cache = T)
library(flipbookr)
library(tidyverse)
library(rmarkdown)
```
layout: true
<div class="my-footer"><span>kathoffman.github.io/swimmer-plots/slides-wcm.html</span></div>
---
name: xaringan-title
class: right, middle
background-image: url(img/blue-foaming-waves-north-beach-nazare-portugal.jpg)
background-size: cover
<h1 style="color: white;">Making swimmer plots for longitudinal data using {ggplot}</h1>
<img src="img/rmed-hex.png" alt="Rmed-hex-sticker" width="180" />
<h3 style="color: white;">Kat Hoffman | WCM Computing Club | September 6, 2022</h3>
---
# Swimmer plot
.pull-left[
- Graphical way to show a **subject's profile over time**
- A series of horizontal lines, in which **each line represents one subject**
- **Colors or shapes** on the line **indicate treatments** or other statuses of that subject at a particular time
]
.pull-right[
```{r echo=F, out.width=600, fig.align="center", fig.cap="Image: Shen et al. Cell 182, 59–72, July 9, 2020"}
knitr::include_graphics("img/cell_swimmer.png")
```
]
<!-- -- -->
<!-- - -->
<!-- -- -->
<!-- - -->
<!-- -- -->
<!-- - Excellent for exploratory data analysis (EDA) of longitudinal data (e.g. visualize missigness or sampling patterns) -->
<!-- -- -->
<!-- - Can be included as a final product (e.g. manuscripts, presentations) to explain cohort composition, treatment variability, and more -->
<!-- -- -->
<!-- - While `R` packages such as `swimmer` exist, it is often faster and more customizable to write end-to-end `ggplot` code yourself -->
---
# Do we *really* have to hand-code this?
.pull-left[
- `R` packages such as `swimplot` do exist, but it is more customizable to write end-to-end `ggplot` code yourself
- Configuring the legend correctly in `ggplot` can be tricky whether you use `swimplot` or not
]
.pull-right[
```{r out.width=500, echo=F, fig.cap="Image courtesy of {swimplot} vignette."}
knitr::include_graphics("img/swimmer_swimplot.png")
```
]
---
.left-column[
### Today's swimmer plot:
We will show the timing of...
- severe hypoxia
- intubation
- steroids administration
- 28-day mortality
...in a cohort of hospitalized COVID-19 patients.
]
.right-column[
```{r echo=F, out.width=700, fig.align="center"}
knitr::include_graphics("img/swimmer.png")
```
]
---
# Step 1: Long-form data set
.pull-left[
- ID column
- Time column (e.g. day)
- One column per status (e.g. drug A - yes/no, drug B - yes/no)
- One row per subject per unit of time
]
--
.pull-right[
```{r data1}
library(tidyverse)
library(data.table)
dat_long <- read_csv("https://raw.githubusercontent.com/kathoffman/steroids-trial-emulation/main/data/dat_trt_timeline.csv",col_types = list(id = "c", steroids = "c", death = "c", severe = "c"))
dat_long |> data.table()
```
]
---
# Step 2: Long-form data for plotting
.pull-left[
- ID column (**optional: order by maximum time per subject**)
- Time column
- One column per status, **which is now the time if you want the status to be marked on the plot**
- One row per subject per unit of time
]
--
.pull-right[
This is a way to create data with a reordered patient ID (by hospital length-of-stay):
```{r data2}
dat_reorder <-
dat_long |>
group_by(id) |>
mutate(max_day = max(day)) |>
ungroup() |>
mutate(id = fct_reorder(factor(id), max_day))
```
The next slide shows how to change the status columns to `{status}_this_day` columns.
]
---
# Step 2: Long-form data for plotting
```{r}
dat_swim <- dat_reorder |>
mutate(severe_this_day = case_when(severe == 1 ~ day),
steroids_this_day = case_when(steroids == 1 ~ day),
death_this_day = case_when(death == 1 ~ day))
dat_swim |> paged_table()
```
---
`r chunk_reveal("swim0", break_type = "user", title="# Step 3: Plot all your geometries")`
```{r swim0, include = FALSE}
dat_swim %>%
ggplot(aes(y=id, group=id)) + #BREAK
theme_bw() + #BREAK
geom_line(aes(x=day, col = intubation_status)) +#BREAK
geom_point(aes(x=steroids_this_day)) +#BREAK
geom_point(aes(x=severe_this_day)) +#BREAK
geom_point(aes(x=death_this_day))
```
---
`r chunk_reveal("swim1", break_type = "user", title="# Step 4: Modify geom_* layers.")`
```{r swim1, include = FALSE}
dat_swim %>%
ggplot(aes(y=id, group=id)) +
theme_bw() + #BREAK
geom_line(aes(x=day, col = intubation_status),
size=1.8) +#BREAK
geom_point(aes(x=steroids_this_day),
stroke=2,
shape = 15) +#BREAK
geom_point(aes(x=severe_this_day),
size=2,
stroke=1.5,
shape = 21) + #BREAK
geom_point(aes(x=death_this_day),
size=2,
stroke=1.5,
shape = 4)
```
---
# Step 5: Add colors and legend
.left-column[

]
.right-column[
**The Big Picture:**
- We want a legend which correctly maps each shape, color, and line type to the corresponding status.
- We need all of our statuses to show up in the legend. They currently do not, because they're not being mapped to an `aes`thetic argument.
- We will force all the statuses to show up by creating a new aesthetic (color) which **corresponds to the name we want each status to be labeled** in the legend.
- We will then modify this legend for "color" to also contain information about shape, linetype, etc. for each status.
]
---
`r chunk_reveal("swim2", break_type = "user", title="# Step 5: Add colors and legend")`
```{r swim2, include = FALSE}
dat_swim %>%
ggplot(aes(y=id)) +
theme_bw() +
geom_line(aes(x=day,
col = intubation_status,
group=id),
size=1.8) + #BREAK
geom_point(aes(x=steroids_this_day,
col="Steroids"),
stroke=2,
shape=15) +#BREAK
geom_point(aes(x=severe_this_day,
col="Severe hypoxia"),
size=2,
stroke=1.5,
shape=21) + #BREAK
geom_point(aes(x=death_this_day,
col="Death"),
size=2,
stroke=1.5,
shape=4)
```
---
# Step 6: Modify colors
- We now need a key for status labels and corresponding colors.
```{r}
# define colors for all geometries with a color argument
cols <- c("Severe hypoxia" = "#b24745", # red
"Intubated" = "#483d8b", # navy
"Not intubated" = "#74aaff", # blue
"Steroids"="#ffd966", # gold
"Death" = "#000000") # black
```
- The label of the status should match the label inputted to `aes(col = "...")`.
- The order of this color key will be the order the statuses appear in the legend.
- We will use this key as the `values` argument of `scale_color_manual()`:
---
`r chunk_reveal("swim3", break_type = "user", title="# Step 6: Modify colors")`
```{r swim3, include = FALSE}
dat_swim %>%
ggplot(aes(y=id)) +
theme_bw() +
geom_line(aes(x=day,
col = intubation_status,
group=id),
size=1.8) +
geom_point(aes(x=steroids_this_day,
col="Steroids"),
stroke=2,
shape=15) +
geom_point(aes(x=severe_this_day,
col="Severe hypoxia"),
size=2,
stroke=1.5,
shape=21) +
geom_point(aes(x=death_this_day,
col="Death"),
size=2,
stroke=1.5,
shape=4) +#BREAK
scale_color_manual(values = cols,
name="Patient Status")
```
---
# Step 7: Modify legend using override.aes()
- We need to create vectors for overriding the aesthetics for `shape`, `linetype`, `stroke`, and `size` in the current "color" legend.
- These should be in the same order as the `cols` key
- If we don't want a certain aesthetic to show up (e.g. no shape for intubation), we use `NA`
```{r}
cols
shape_override <- c(21, NA, NA, 15, 4) # order matches `cols`:severe, intubation (yes/no), steroids, death
line_override <- c(NA,1,1,NA,NA) # order matches `cols`:severe, intubation (yes/no), steroids, death
stroke_override <- c(.8,1,1,1,1) # order matches `cols`:severe, intubation (yes/no), steroids, death
size_override <- c(2.5,2.5,2.6,2,2) # order matches `cols`:severe, intubation (yes/no), steroids, death
```
---
`r chunk_reveal("swim4", break_type = "user", title="# Step 7: Modify legend using override.aes()")`
```{r swim4, include = FALSE}
dat_swim %>%
ggplot(aes(y=id)) +
theme_bw() +
geom_line(aes(x=day, col = intubation_status, group=id),
size=1.8) +
geom_point(aes(x=steroids_this_day, col="Steroids"),
stroke=2, shape=15) +
geom_point(aes(x=severe_this_day, col="Severe hypoxia"),
size=2, stroke=1.5, shape=21) +
geom_point(aes(x=death_this_day, col="Death"),
size=2, stroke=1.5, shape=4) +
scale_color_manual(values = cols,
name="Patient Status") + #BREAK
guides(color = guide_legend(
override.aes = list(
stroke = stroke_override,
size = size_override,
shape = shape_override,
linetype = line_override)
))
```
```{r echo=F }
p <- dat_swim %>%
ggplot(aes(y=id)) +
theme_bw() +
geom_line(aes(x=day,
col = intubation_status,
group=id),
size=1.8) +
geom_point(aes(x=steroids_this_day,
col="Steroids"),
stroke=2,
shape=15) +
geom_point(aes(x=severe_this_day,
col="Severe hypoxia"),
size=2,
stroke=1.5,
shape=21) +
geom_point(aes(x=death_this_day,
col="Death"),
size=2,
stroke=1.5,
shape=4) +
scale_color_manual(values = cols,
name="Patient Status") + #BREAK
guides(color = guide_legend(
override.aes = list(
stroke = stroke_override,
size = size_override,
shape = shape_override,
linetype = line_override)
))# BREAK
```
---
`r chunk_reveal("swim5", break_type = "user", title="# Step 8: Make minor theme edits")`
```{r swim5, include = FALSE}
p + labs(x="Days since hospitalization",
y="Patient\nnumber",
title="Treatment Timeline for N=30 Patients") + #BREAK
scale_x_continuous(expand=c(0,0)) + #BREAK
theme(text=element_text(family="Poppins", size=11)) +
theme(title = element_text(angle = 0, vjust=.5,
size=12, face="bold"),
axis.title.y = element_text(angle = 0, vjust=.5,
size=12, face="bold"),
axis.title.x = element_text(size=15, face="bold",
vjust=-0.5, hjust=0),
axis.text.y = element_text(size=6,
hjust=1.5),
axis.ticks.y = element_blank()) + #BREAK
theme(legend.position = c(0.8, 0.3),
legend.title = element_text(colour="black",
size=13,
face=4),
legend.text = element_text(colour="black",
size=10),
legend.background = element_rect(size=0.5,
linetype="solid",
colour ="gray30")) + #BREAK
theme(panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank()
)
```
```{r include=F, eval=F, echo=F}
p_final <- p + labs(x="Days since hospitalization",
y="Patient\nnumber",
title="Treatment Timeline for N=30 Patients") + #BREAK
scale_x_continuous(expand=c(0,0)) + #BREAK
theme(text=element_text(family="Poppins", size=11)) +
theme(title = element_text(angle = 0, vjust=.5,
size=12, face="bold"),
axis.title.y = element_text(angle = 0, vjust=.5,
size=12, face="bold"),
axis.title.x = element_text(size=15, face="bold",
vjust=-0.5, hjust=0),
axis.text.y = element_text(size=6,
hjust=1.5),
axis.ticks.y = element_blank()) + #BREAK
theme(legend.position = c(0.8, 0.3),
legend.title = element_text(colour="black",
size=13,
face=4),
legend.text = element_text(colour="black",
size=10),
legend.background = element_rect(size=0.5,
linetype="solid",
colour ="gray30")) + #BREAK
theme(panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank()
)
ggsave("img/swimmer.png", width=8, height=6)
```
---
# In Summary 🏊
.pull-left[
- Long-format plotting data will need to have one column per status per row which indicates the **time of the status marker** to be denoted.
- Once data is properly formatted, `ggplot` can be used to make customizable swimmer plots with the `geom_line` and `geom_point` layers.
- The legend can be properly configured using the `override.aes()` argument in `guides()`.
- These ideas can be extended in many ways, such as [**showing the pattern of missing data**](https://www.khstats.com/blog/trt-timelines/trt-timelines/).
]
--
.pull-right[
```{r, echo=F, out.width=400, fig.cap = "Image from Patient Treatment Timelines for Longitudinal Survival Data -- KHstats, 2019"}
knitr::include_graphics("img/trt-timeline-missing.png")
```
]
<!-- adjust font size in this css code chunk, currently 80 -->
```{css, eval = TRUE, echo = FALSE}
.remark-code{line-height: 1.5; font-size: 80%}
@media print {
.has-continuation {
display: block;
}
}
code.r.hljs.remark-code{
position: relative;
overflow-x: hidden;
}
code.r.hljs.remark-code:hover{
overflow-x:visible;
width: 500px;
border-style: solid;
}
```
---
# Questions?
Swimmer plot blog posts:
["Longitudinal Treatment Timelines in R"](https://www.khstats.com/blog/trt-timelines/trt-timelines/)
["Using ggplot2 to create Treatment Timelines with Multiple Variables"](https://www.khstats.com/blog/trt-timelines/multiple-vars/)
<img src="img/climbing_comic.jpeg" width="250"/>
Slides: `{xaringan}` + `{flipbookr}`