/
2019-02-27_presidents-day.Rmd
1359 lines (1148 loc) · 44.2 KB
/
2019-02-27_presidents-day.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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "President's Day (As In: What Does President Trump Do With His Day?)"
twitterTitle: "President's Day"
author: Garrick Aden-Buie
date: '2019-02-27'
slug: presidents-day
aliases: /blog/2019/02/27/presidents-day
categories:
- Blog
tags:
- R
- rtweet
- ggplot2
- Visualization
- Politics
Keywords: ["rstats", "rtweet", "ggplot2", "tidyverse", "data cleaning", "data visualization", "politics", "trump", "tweets"]
Description: |
As in: What does Presdient Trump do with his day? (Spoiler: A whole lot of "executive time".)
twitterImage: "/blog/2019/2019-02-27_presidents-day_files/figure-html/plot-time-category-total-pct-1.png"
rmd_source: https://github.com/gadenbuie/garrickadenbuie-com/blob/master/content/blog/2019/2019-02-27_presidents-day.Rmd
head_custom: |
<link href="https://fonts.googleapis.com/css?family=PT+Mono" rel="stylesheet">
output:
blogdown::html_page:
section_divs: false
---
<!-- links -->
[axios-article]: https://www.axios.com/donald-trump-private-schedules-leak-executive-time-34e67fbb-3af6-48df-aefb-52e02c334255.html
[axios-spreadsheet]: https://docs.google.com/spreadsheets/d/1oITCuVsYdhNXtY7GElLelsrbjRRIPJ1ce-_v-8J1X_A/edit#gid=0
[axios-comparison]: https://www.axios.com/donald-trump-schedule-obama-bush-clinton-513c73ff-4d15-4e7a-9676-334557a894ee.html
[vox-exec-time]: https://www.vox.com/policy-and-politics/2019/2/4/18210345/trump-executive-time-axios-private-schedule-leak
[politico-exec-time]: https://www.politico.com/story/2018/10/29/trump-daily-schedule-executive-time-944996
[maelle-rectangle]: https://masalmon.eu/2019/02/11/trump-schedule/
[yonicd-app]: https://potus-private-schedule.herokuapp.com/
[plot.ly]: https://plot.ly
[tidyverse]: https://tidyverse.org
[so-rev-date]: https://stackoverflow.com/a/43626186
[tidyeval]: https://tidyeval.tidyverse.org/
[hrbrthemes]: https://hrbrmstr.github.io/hrbrthemes/
[rtweet]: https://rtweet.info
[so-plotly]: https://stackoverflow.com/a/45802923/2022615
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE, warning = FALSE, message = FALSE,
fig.width = 9, fig.height = 10, fig.show = "hide"
)
options(htmltools.dir.version = TRUE)
```
```{r library, results="hide"}
library(tidyverse)
library(lubridate)
library(hrbrthemes)
library(showtext)
library(sysfonts)
library(glue)
```
```{r function-in_hours}
# Convert datetime to decimal hour of day
in_hours <- function(x) {
hour(x) + minute(x)/60 + second(x)/60^2
}
```
```{r function-executive_categories}
executive_categories <- c(
"executive_time" = "Executive Time",
"event" = "Event",
"lunch" = "Lunch",
"meeting" = "Meeting",
"no_data" = "Unknown",
"travel" = "Travel"
)
```
```{r function-filter_workday}
filter_workday <- function(
df,
start = hms::hms(0, 0, 8),
end = hms::hms(0, 0, 17),
start_var = time_start,
end_var = time_end
) {
start_var <- rlang::enquo(start_var)
end_var <- rlang::enquo(end_var)
df %>%
filter(
date(!!start_var) == date(!!end_var),
hms::as.hms(!!start_var) >= start,
hms::as.hms(!!end_var) <= end
)
}
```
```{r load-exec-time}
# Exec Time Downloaded from http://bit.ly/2Sk9Vj7
exec_time <-
read_csv(
here::here(
"_data", "trump-exec-time",
"axios_trump_schedule_2018-11-07--2019-02-02.csv"
),
col_types = cols(.default = col_character())
) %>%
mutate(
# Convert time start/end to datetime
event_id = row_number(),
time_start = paste(date, time_start),
time_end = paste(date, time_end),
time_start = ymd_hm(time_start, tz = "America/New_York"),
time_end = ymd_hm(time_end, tz = "America/New_York"),
time_end = if_else(time_start > time_end,
time_end + hours(24), time_end),
# Recode the activity category with nicer labels
top_category = factor(top_category,
levels = names(executive_categories),
labels = executive_categories)
) %>%
mutate(
# Create label pieces for plotly hover text
label_title = glue("<b>{top_category}</b>"),
has_uniq_title = tolower(top_category) != tolower(listed_title),
has_subtitle = has_uniq_title & !is.na(listed_title),
label_subtitle = if_else(has_subtitle,
glue("<br><em>{listed_title}</em>"), ""),
has_location = !is.na(listed_location),
label_location = if_else(has_location,
glue("<br><em>{listed_location}</em>"), ""),
label_time = glue(
"<br><br>{strftime(time_start, '%A, %B %e %H:%M')} ",
"to {strftime(time_end, '%H:%M')}"),
has_notes = !is.na(notes),
label_notes = if_else(has_notes, paste0("<br><br>", notes), ""),
# Compose final tooltip text
label = paste0(label_title, label_subtitle, label_location,
label_time, label_notes)
) %>%
mutate(
# truncate any activities that span 8am or 5pm
time_start = if_else(
in_hours(time_start) < 8 & in_hours(time_end) > 8,
floor_date(time_start, "day") + hours(8),
time_start
),
time_end = if_else(
in_hours(time_start) < 17 & in_hours(time_end) > 17,
floor_date(time_end, "day") + hours(17),
time_end
),
# create 5 minute increments "inside" each activity
time_inc = map2(time_start, time_end, seq, by = "5 mins")
) %>%
select(event_id, time_start, time_end, time_inc,
listed_title, top_category, label)
```
```{r get-djt-tweets, eval = FALSE}
if (FALSE) {
djt <- NULL
keep_going <- TRUE
while (keep_going) {
max_id <- if (!is.null(djt$status_id)) max(as.numeric(djt$status_id))
djt.this <- rtweet::get_timeline("realdonaldtrump", n = 3200, max_id = max_id)
djt <- bind_rows(djt, djt.this)
keep_going <- min(djt$created_at) > lubridate::ymd_h("2018-11-07 0", tz = "America/New_York")
cat("\nWe have", nrow(djt), "tweets...")
Sys.sleep(15)
}
saveRDS(djt, here::here("_data", "djt-tweets-2018-09--2019-02.rds"))
}
```
```{r load-djt-tweets}
djt <- readRDS(here::here("_data", "djt-tweets-2018-09--2019-02.rds")) %>%
distinct(status_id, .keep_all = TRUE)
```
```{r djt-tweets}
djt_simple <-
djt %>%
filter(!is_retweet) %>%
mutate(
created_at = with_tz(created_at, tzone = "America/New_York"),
time_inc = floor_date(created_at, "5 min")
) %>%
select(created_at, time_inc, text, status_id)
djt_joined_all <-
exec_time %>%
unnest() %>%
filter(time_end != time_inc) %>%
full_join(djt_simple, by = "time_inc") %>%
select(
event_id, starts_with("time_"), created_at,
listed_title, top_category, text
) %>%
filter(
!is.na(text)
) %>%
distinct(text, .keep_all = TRUE) %>%
mutate(
hour = in_hours(created_at),
date = floor_date(created_at, "day"),
top_category = factor(top_category, executive_categories),
label_sched = if_else(
wday(created_at, abbr = FALSE, week_start = 1) >= 6,
glue("<br>During: <b>Weekend</b>"),
glue(
"<br>During: <b>{top_category}</b>",
"<br>Sched: {strftime(time_start, '%I:%M')} ",
"to {strftime(time_end, '%I:%M %p')}")
),
label = glue("{str_wrap(text, 50)}",
"<br><i>@realDonaldTrump ",
"{strftime(created_at, '%a, %b %e, %I:%M %p')}</i>",
"{label_sched}")
) %>%
select(-time_start, -time_end, -label_sched) %>%
arrange(created_at)
djt_joined <-
djt_joined_all %>%
filter(!is.na(top_category))
```
```{r functions-am-pm}
am_pm <- function(x) {
x <- floor(x)
y <- paste(x)
y[x < 1] <- "12 am"
y[x > 1 & x < 12] <- paste(y[x > 1 & x < 12], "am")
y[x == 12] <- "12 pm"
y[x > 12] <- paste(x[x > 12] - 12, "pm")
y
}
```
```{r functions-rev-date}
# Reverse Time Axis
# thanks: https://stackoverflow.com/a/43626186
c_trans <- function(a, b, breaks = b$breaks, format = b$format) {
library(scales)
a <- as.trans(a)
b <- as.trans(b)
name <- paste(a$name, b$name, sep = "-")
trans <- function(x) a$trans(b$trans(x))
inv <- function(x) b$inverse(a$inverse(x))
trans_new(name, trans, inverse = inv, breaks = breaks, format=format)
}
rev_date <- c_trans("reverse", "time")
```
```{r functions-lightbox-img}
lightbox_img <- function(url, alt = "", caption = "", preview = TRUE) {
if (preview) {
glue::glue(
'<a href="{url}" data-featherlight="image">
<div class="figure">
<img src="{url}" alt="{alt}">
<p class="caption">{caption}</p>
</div>
</a>
'
)
} else {
if (alt == "") alt <- "static image of the plot"
glue::glue('<a href="{url}" data-featherlight="image">{alt}</a>')
}
}
```
```{r plot-theme-fonts}
sysfonts::font_add_google("PT Sans")
sysfonts::font_add_google("PT Sans Narrow")
sysfonts::font_add_google("PT Mono")
showtext::showtext_auto()
```
```{r plot-theme}
theme_set(
hrbrthemes::theme_ipsum(
base_family = "PT Sans",
base_size = 20,
axis_title_family = "PT Sans Narrow",
axis_title_size = 14,
axis_text_size = 12,
axis_title_just = "c"
) +
theme(
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5),
plot.margin = margin(15, 15, 15, 15),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
legend.position = "bottom",
legend.key = element_rect(
fill = "white", color = "white", size = 4),
legend.key.width = unit(2, "cm"),
legend.text = element_text(size = 9),
plot.caption = element_text(
color = "#85919b", hjust = 0, size = 12, face = "plain")
)
)
```
```{r plot-vars}
plot_date_breaks <- seq(
from = ymd_h("2018-11-12 0", tz = "America/New_York"),
to = max(exec_time$time_start),
by = "7 day")
event_type_colors <- c(
"Executive Time" = "#445566",
"Travel" = "#997788",
"Lunch" = "#7c9393",
"Meeting" = "#b7c6d6",
"Event" = "#ddbbaa",
"Unknown" = "#d9dde0")
event_type_labels <- sub(" ", "\n", names(event_type_colors))
```
```{r plot-credit-caption}
credit_caption <- function(rtweet = FALSE) {
paste0(
"\nData: Based on White House schedules released by Axios. http://bit.ly/2UGM0fw",
if (rtweet) "\n Tweets collected with {rtweet}. https://rtweet.info",
"\nChart: @grrrck"
)
}
```
On February 3rd, Axios [released President Trump's daily schedule][axios-article].
As in many other areas of his political career, Trump has broken with tradition by hiding his schedule from public view.
In addition to a set of re-typed PDF files, Axios also created a [Google Spreadsheet][axios-spreadsheet] containing the president's schedule and notes about the activities.
If you're interesting in reading about how that task could be accomplished, I highly recommend Maëlle Salmon's post on [rectangling the tables in the PDF files][maelle-rectangle].
The leak and subsequent release by Axios provide unique insight into Trump's daily activities, which are dominated by a large block of time referred to as **Executive Time**.
Reportedly, Trump hated following a strict daily schedule, so former chief-of-staff John Kelly introduced the concept of Executive Time: unstructured time when the president ~~reads~~ watches news, makes phone calls, and writes ~~emails~~ tweets.
I won't comment extensively on what these schedules mean---for more on that angle, see reporting from [Axios][axios-comparison], [Vox][vox-exec-time], [Politico][politico-exec-time] and others.
Instead, I'll use this post to visualize the president's work day and tweeting habits and a demonstrate how to use R, [plot.ly] and the tools of the [tidyverse] to create interactive and static visualizations to try to make sense of what the president does on a daily basis.
## The President's Daily 8am to 5pm Schedule
Axios' [article on Trump's private schedule][axios-article] includes an interactive view of the president's workday schedule from 8 a.m. to 5 p.m.
Here, I recreate the same visualization, with each activity colored according to the activity's category.
(Note these plots look best on desktop devices.)
Hover over any time slot to view more details about the activity at that time.
You can also toggle activity categories --- try removing everything except **Meeting**s, **Lunch**es, and **Event**s, it's unbelievable.
```{r plot-daily-schedule, fig.show = "show", out.width="115%"}
g <-
exec_time %>%
mutate(date = floor_date(time_start, "day")) %>%
filter_workday() %>%
mutate_at(vars(time_start, time_end), in_hours) %>%
ggplot() +
geom_rect(
aes(xmin = time_start,
xmax = time_end,
ymin = date - 3600 * 12,
ymax = date + 3600 * 12,
fill = top_category)
) +
scale_x_continuous(
breaks = seq(8, 17, 3),
limits = c(8, 17),
position = "top",
labels = am_pm(seq(8, 17, 3)),
expand = expand_scale(c(0.025, 0), 0)
) +
scale_y_continuous(
trans = rev_date,
breaks = plot_date_breaks,
labels = strftime(plot_date_breaks, "%b %e"),
expand = expand_scale(c(0.025, 0), 0)
) +
scale_fill_manual(
values = event_type_colors,
labels = event_type_labels
) +
labs(x = "Hour of the Day", y = NULL, fill = NULL) +
ggtitle(
"President Trump's Daily Schedule",
"November 7, 2018 through February 2, 2019"
) +
labs(caption = credit_caption(FALSE)) +
guides(fill = guide_legend(nrow = 1, label.position = "bottom")) +
theme(
axis.text.y = element_text(family = "PT Mono", size = 10),
plot.margin = margin(3, 0, 0, 0, unit = "line")
)
plotly::ggplotly(g + aes(text = label), tooltip = "label") %>%
plotly::layout(xaxis = list(side = "top", title = ""))
```
```{r plot-daily-schedule-static, dependson="plot-daily-schedule"}
g +
theme(plot.margin = margin(0, 15, 0, 15))
```
View `r lightbox_img(knitr::fig_chunk("plot-daily-schedule-static", "png"), preview = FALSE)`.
Expand the section below for a behind-the-scenes look at this visualization.
### How This Was Made... {.js-expandmore}
<div class="js-to_expand">
The pipeline for building this visualization is a fairly standard loading and transformation of the source data with `readr` and `dplyr`, followed by building the visualization in `ggplot2` and passing off to `plotly` for the interactive parts.
On the other hand, I created a number of helper functions and constants that I reused throughout this post, so there's quite a bit of code and preamble to get to the actual plot making.
```r
library(tidyverse)
library(plotly)
library(lubridate)
library(glue)
library(hrbrthemes)
library(showtext)
library(sysfonts)
```
#### Load the Axios Data
```{r view-load-axios, eval=FALSE, echo=TRUE}
<<function-in_hours>>
<<function-executive_categories>>
<<load-exec-time>>
glimpse(exec_time)
```
```{r view-exec-time}
glimpse(exec_time)
```
#### Prepare to Make a Plot
To build the plot, I first created several helper functions for the plot labels, scales, and data filtering.
I also set the global plot theme, and created a few constants that I used across several plots in this post.
##### Helper Functions {.js-expandmore}
<div class="js-to_expand">
The first helper adds `"am"` or `"pm"` to an integer hour for easy-to-read labels on the x-axis _time of day_.
```{r view-am-pm, echo = TRUE}
<<functions-am-pm>>
am_pm(seq(8, 17, 3))
```
The second helper function is copied directly from [StackOverflow: Reverse datetime (POSIXct data) axis in ggplot][so-rev-date], in one of the rare-but-beautiful moments when directly copying and pasting from SO works out perfectly.
This gives me a `rev_date()` transformer function that can be passed to `scale_y_continuous(trans = rev_date)` to show the y-axis in chronological order with the earliest date starting at the top.
A third helper function abstracts the code required to filter out the portion of the data set that belongs to the workday, which I use throughout this post.
This function is a nice example of how [tidyeval] can be used for flexible dplyr wrapper functions.
```{r view-filter-workday, echo=TRUE, eval=FALSE}
<<function-filter_workday>>
```
Finally, another helper function creates the plot caption credits.
```{r view-caption-credit, echo=TRUE, eval=FALSE}
<<plot-credit-caption>>
```
</div>
##### Plot Themes {.js-expandmore}
<div class="js-to_expand">
I used `showtext` and `sysfonts` to match the fonts in the plot to the font used on this blog (PT Mono).
```{r view-plot-fonts, eval=FALSE, echo=TRUE}
<<plot-theme-fonts>>
```
And I used [hrbrthemes'][hrbrthemes] excellent `theme_ipsum()` as my theme's starting point.
```{r view-plot-theme, eval=FALSE, echo=TRUE}
<<plot-theme>>
```
</div>
##### Plot Constants {.js-expandmore}
<div class="js-to_expand">
I created a few constants for later reference: one stores date breaks for the time period covered by the Axios schedule, with labels on each Monday; and the other two store the color palette and labels for the executive activity categories.
The colors were hand-selected from a picture of the Donald (I was expecting there to be more orange).
```{r view-plot-constants, echo=TRUE, eval=FALSE}
<<plot-vars>>
```
```{r view-plot-colors, fig.width=4, fig.height=3}
scales::show_col(event_type_colors)
```
<div style="width: 100%">
<img src="`r knitr::fig_chunk("view-plot-colors", "png")`" style="max-width: 300px; margin: auto;" />
</div>
</div>
#### Build the Actual Plot Already!
Finally, I pulled the schedule data and all of the above pieces together to build the interactive plot.
```{r view-plot-daily-schedule, eval=FALSE, echo=TRUE}
<<plot-daily-schedule>>
```
And that's it!
[Jump back up](#the-presidents-daily-8am-to-5pm-schedule) to see the final product.
</div>
## The President's Daily Tweeting Schedule
```{r djt-workday}
djt_axios_sched <-
djt_joined_all %>%
filter(date >= "2018-11-07", date <= "2019-02-02") %>%
mutate(
weekend = wday(created_at, abbr = FALSE, week_start = 1) >= 6,
weekend = if_else(weekend, "weekend", "weekday")
) %>%
select(-text)
djt_workday <-
djt_axios_sched %>%
filter_workday(
start_var = created_at, end_var = created_at
)
```
```{r djt-workday-for-text}
djt_per_workday <-
djt_axios_sched %>%
filter_workday(
start_var = created_at, end_var = created_at
) %>%
group_by(weekend) %>%
count(date) %>%
summarize(
tweets = sum(n),
n = n(),
mean = tweets/n) %>%
split(.$weekend)
djt_per_day <-
djt_axios_sched %>%
group_by(weekend) %>%
count(date) %>%
summarize(
tweets = sum(n),
n = n(),
mean = tweets/n) %>%
split(.$weekend)
```
Donald Trump tweets about
`r round(djt_per_workday$weekday$mean, 1)`
tweets per working day within working hours.
Why does this number feel so low?
Then again, this represents
`r djt_per_workday$weekday$tweets`
tweets published over
`r djt_per_workday$weekday$n`
workdays and
`r djt_per_workday$weekend$tweets`
tweets over the
`r djt_per_workday$weekend$n`
weekend days in the same time period.
Outside of work hours, the average rises to
`r round(djt_per_day$weekday$mean, 1)`
tweets per 24-hour workday,
or a total of
`r djt_per_day$weekday$tweets`
tweets on workdays and
`r djt_per_day$weekend$tweets`
tweets on weekends.
Below, each tweet sent by the President is shown as a dot over his private schedule.
Hover over a tweet's dot to read the text of the tweet.
```{r plot-tweets-over-category, fig.show = "show", out.width="115%"}
# Modify geom_rect (only layer) to reduce transparency
g_subdued <- g
g_subdued$layers[[1]]$aes_params$alpha <- 0.6
# Add tweets to the plot
g_subdued <-
g_subdued +
ggtitle("President Trump's Daily Tweeting") +
geom_point(
data = djt_workday,
aes(x = hour, y = date + 3600, text = label),
color = "#2c3741",
size = 0.8
)
gpltly <-
plotly::ggplotly(g_subdued, tooltip = "label") %>%
plotly::layout(xaxis = list(side = "top", title = ""))
# remove hover labels for time category layers (6 categories)
# thanks: https://stackoverflow.com/a/45802923/2022615
for (i in 1:6) {
gpltly$x$data[[i]]$hoverinfo <- "none"
}
# Final Plot!
gpltly
```
```{r plot-tweets-over-category-static}
g_subdued +
theme(plot.margin = margin(0, 15, 0, 15))
```
View `r lightbox_img(knitr::fig_chunk("plot-tweets-over-category-static", "png"), preview = FALSE)`.
Expand the section below to learn more about how I gathered tweets from @realDonaldTrump, merged his tweets with the Axios schedules, and added them to the first plot.
Also, if you're interested in exploring the timeline of tweets rendered as they appear on Twitter, Jonathan Sidi created an awesome Shiny app for [exploring Trump's tweets by category][yonicd-app].
### How This Was Made... {.js-expandmore}
<div class="js-to_expand">
This visualization required the President's tweets, which I downloaded using the excellent [rtweet] package.
After matching the tweets with their corresponding activity, I modified the previous plot to soften the coloring of the presidential activities and added the tweets to the chart.
#### Download the President's Tweets
Using the [rtweet] package makes downloading the tweets relatively straightforward.
I only needed to add a loop to gather tweets beyond Twitter's timeline API limits and ensure that I have all the tweets from the time period described in the leaked schedules.
```{r view-get-djt-tweets, echo=TRUE, eval=FALSE}
# Change to `if (TRUE)` to run
<<get-djt-tweets>>
```
#### Join Tweets with the President's Schedule
To align the tweets with the President's schedule, I rounded (actually, floored) the time stamp of each tweet down to the nearest 5 minute interval.
Then, I joined the tweets to the schedule using the 5 minute intervals I created while importing the schedule (see above).
This gives me the category and scheduled activity of each tweet.
```{r view-djt-tweets, eval=FALSE, echo=TRUE}
<<djt-tweets>>
```
Finally, I still need to do a little bit of processing to get these tweets to fit into the previous plot.
```r
djt_workday <-
djt_joined_all %>%
filter_workday(
start_var = created_at, end_var = created_at
) %>%
filter(date >= "2018-11-07", date <= "2019-02-02") %>%
select(-text)
```
At this point, there are a few versions of the tweets data set that I can use in different places.
The `djt_simple` is a basic, bare-bones tibble of tweets.
```{r view-djt-simple}
djt_simple %>%
arrange(created_at) %>%
filter(created_at >= "2018-11-07")
```
The `djt_joined_all` variable holds the complete set of all tweets joined with the full schedule, meaning that there will be missing values where no tweets occurred in a 5 minute window or where the schedule data doesn't cover a tweet.
```{r view-djt-joined-all}
set.seed(4242)
top_10 <- sample(1:nrow(djt_joined_all), 10)
header_rows <- c(
sort(top_10),
setdiff(1:nrow(djt_joined_all), top_10)
)
djt_joined_all %>%
slice(header_rows) %>%
select(time_inc, top_category, text, everything())
```
And `djt_workday` contains the tweets within the period covered by the Axios schedules and during workday hours.
```{r view-djt-workday}
djt_workday %>%
select(time_inc, top_category, label, everything())
```
#### Add Tweets to the Schedule Plot
To build the second plot, I had to manually tweak the first plot to adjust the transparency of the `geom_rect` layer and then overlay the tweets as points.
```r
`r paste(knitr:::knit_code$get("plot-tweets-over-category")[1:14], collapse = "\n")`
```
At this point, the plot is almost ready to go, except for the fact that the tooltip text will appear for the underlying activity layers.
Fortunately, once again [StackOverflow][so-plotly] comes to the rescue.
To disable the tooltip, I have to save the plotly object and change the `$hoverinfo` value to `"none"` for each of the data layers of the activity categories.
```r
`r paste(knitr:::knit_code$get("plot-tweets-over-category")[16:25], collapse = "\n")`
```
Head [back to the visualization](#the-presidents-daily-tweeting-schedule) to view the final product and explore Trump's ~~delusional ranting~~ tweets.
</div>
## How much time is spent in Executive Time?
Looking at the above plots, it's really striking how much time is unstructured _Executive Time_ in Trump's schedule.
But how much of the day is spent in each activity group?
##### R code... {#code-time-summary .js-expandmore .expand-for-code}
<div class="js-to_expand">
The first step is to calculate the total time as a percentage of the 8am to 5pm workday spent in each time category.
This data frame will be used for several plots.
One tricky point is that there are piece of the schedule that are explicitly marked as "Unknown" (or "no data") in the Axios data, so I calculate the total percent of time spent in other categories and subtract this value from 1 to recover the complete unaccounted-for time.
```{r exec-time-total-pct, echo = TRUE}
exec_time_total <-
exec_time %>%
filter(between(hour(time_start), 8, 17), hour(time_start) < 17) %>%
mutate(
date = floor_date(time_start, "day"),
n = difftime(time_end, time_start, units = "mins"),
n = as.numeric(n)
) %>%
group_by(date, top_category) %>%
summarize(pct = sum(n) / (60 * 9)) %>%
ungroup() %>%
# Get unaccounted time for each date (unknown or unlabelled)
nest(-date) %>%
mutate(
total = map_dbl(data, ~ {
filter(., top_category != "Unknown") %>%
pull(pct) %>%
sum()
}),
unaccounted = 1 - total,
) %>%
unnest() %>%
spread(top_category, pct, fill = 0) %>%
mutate(`Unknown` = unaccounted) %>%
select(-total, -unaccounted) %>%
gather("top_category", "pct", -date) %>%
mutate(top_category = factor(top_category, rev(names(event_type_colors))))
exec_time_total %>%
arrange(date, desc(pct))
```
The above tibble contains a summary of time use by day, but the first plot requires a full summary of all days in the schedule.
The following code chunk caculates total hours spent in each group and creates a text label that is used to label the regions of the stacked bar in the plot.
```{r exec-time-total-hours, echo=TRUE}
exec_time_hours <-
exec_time_total %>%
# Only the days covered by the schedule
filter(!(pct == 1 & top_category == "Unknown")) %>%
group_by(top_category) %>%
summarize(hours = sum(pct * 60 * 90)) %>%
arrange(desc(top_category)) %>%
mutate(
pct = hours / sum(hours),
pct_upto = cumsum(pct),
label = glue("{top_category}\n",
"{scales::percent(pct, accuracy = 1)}"),
label = if_else(top_category == "Unknown", "", paste(label))
)
exec_time_hours
```
Finally, I create the plot using `geom_col()` to create a stacked bar chart, that I then rotate to be horizontal with `coord_flip()`.
The bar labels are added as a text annotation, and I do a little adjustment to make sure the annotations fit in the plot and to hide the axis that aren't relevant.
```{r plot-time-category-total-pct, fig.height=4, echo = TRUE}
ggplot(exec_time_hours) +
aes(x = 1,
y = pct,
fill = top_category) +
geom_col() +
geom_text(
aes(x = 0.35, y = pct_upto - pct/2, label = label),
color = "grey30",
family = "PT Sans"
) +
scale_fill_manual(
values = event_type_colors,
labels = rev(event_type_labels),
guide = FALSE
) +
scale_x_continuous(
expand = expand_scale(0, c(0.2, 0))
) +
scale_y_continuous(
labels = scales::percent_format(accuracy = 10),
expand = expand_scale(0, 0),
position = "bottom"
) +
coord_flip() +
labs(
x = NULL,
y = "Percent of Workday Between 8am and 5pm",
fill = NULL
) +
ggtitle(
"What Does President Trump Do With His Time?"
) +
labs(caption = credit_caption(FALSE)) +
theme(
axis.text.y = element_blank(),
panel.grid.major = element_blank(),
axis.ticks.x.top = element_line(color = "grey20")
)
```
</div>
`r lightbox_img(knitr::fig_chunk("plot-time-category-total-pct", "png"))`
```{r exec-time-summary}
untracked_days <-
exec_time_total %>%
filter(
top_category == "Unknown",
pct ==1
) %>%
pull(date)
exec_time_summary <-
exec_time_total %>%
complete(
date = seq(min(.$date), max(.$date), by = "DSTday"),
top_category
) %>%
filter(
top_category == "Executive Time",
!date %in% untracked_days
) %>%
replace_na(list(pct = 0)) %>%
mutate(weekday = wday(date, abbr = FALSE, week_start = 1) < 6)
exec_time_n_weekdays <-
exec_time_summary %>%
filter(weekday) %>%
nrow()
exec_time_gt_half <-
exec_time_summary %>%
filter(weekday, pct >= 0.5) %>%
nrow()
```
For
**`r exec_time_gt_half`**
of the
**`r exec_time_n_weekdays`**
workdays
(that's **`r scales::percent(exec_time_gt_half/exec_time_n_weekdays)`**)
covered by the Axios schedules and for which there is schedule information,
Trump spent 50% _or more_ of his day in executive time.
In other words, there were only
**`r exec_time_n_weekdays - exec_time_gt_half`**
days in about
**`r round(exec_time_n_weekdays/5, 0)`**
work weeks where executive time was not the dominant activity.
When the above time-use summary is expanded into his daily schedule, it's clear how unusual it is for Trump to spend a significant portion of his day in structured events.
##### R code... {#code-time-category-pct-daily .js-expandmore .expand-for-code}
<div class="js-to_expand">
```{r plot-time-category-pct-daily, echo=TRUE}
ggplot(exec_time_total) +
aes(date + 3600*12, pct, fill = top_category) +
geom_col(width = 3600*24) +
scale_fill_manual(
values = event_type_colors,
labels = rev(event_type_labels)
) +
scale_y_continuous(
breaks = seq(0, 1, .25),
labels = scales::percent_format(accuracy = 25),
position = "bottom",
expand = expand_scale(c(0.025, 0), 0)
) +
scale_x_continuous(
trans = rev_date,
breaks = plot_date_breaks,
labels = strftime(plot_date_breaks, "%b %e"),
expand = expand_scale(c(0.025, 0), 0)
) +
coord_flip() +
labs(
x = NULL,
y = "Percent of Workday Between 8am and 5pm",
fill = NULL
) +
guides(
fill = guide_legend(nrow = 1,
reverse = TRUE,
label.position = "bottom")
) +
ggtitle(
"What Does President Trump Do With His Time?"
) +
labs(caption = credit_caption(FALSE))
```
</div>
`r lightbox_img(knitr::fig_chunk("plot-time-category-pct-daily", "png"))`
In fact, the largest non-executive time block for the
`r exec_time_n_weekdays - exec_time_gt_half`
days where executive time isn't more than half of Trump's workday are almost entirely travel related.
##### R code... {#code-table-not-full-on-exec-time-day .js-expandmore .expand-for-code}
<div class="js-to_expand">
```{r table-not-full-on-exec-time-day, results="asis", echo=TRUE, eval=FALSE}
exec_time_summary %>%
filter(pct < 0.5, weekday) %>%
select(date) %>%
left_join(exec_time %>% mutate(date = floor_date(time_start, "day"))) %>%
mutate(duration = difftime(time_end, time_start, unit = "hours")) %>%
select(date, duration, listed_title) %>%
arrange(date, desc(duration)) %>%
filter(listed_title != "Executive time") %>%
group_by(date) %>%
slice(1) %>%
mutate(duration = round(duration, 2)) %>%
knitr::kable(col.names = c(
"Date", "Duration", "Longest Non-Executive-Time Activity"
), format = "html") %>%
kableExtra::column_spec(1:2, width = "6.5em")
```
</div>
```{r table-not-full-on-exec-time-day-out, results="asis"}
<<table-not-full-on-exec-time-day>>
```
Travel seems to be the only activity capable of substantially affecting the amount of time the president spends on his executive time.
My (completely speculative) guess is that this is in part due to travel being the only activity with a duration long enough to displace executive time, and also in part that travel probably most resembles executive time.
##### R code... {#code-plot-exec-time-vs-others .js-expandmore .expand-for-code}
<div class="js-to_expand">
```{r plot-exec-time-vs-others, fig.width=8, fig.height=3, echo=TRUE}
exec_time_total %>%
# Drop "Unkown" time category, not that important
filter(top_category != "Unknown") %>%
# Spread top_category...
spread(top_category, pct) %>%
# ...and gather to leave Executive Time in own column
gather(other_activity, pct, -date, -`Executive Time`) %>%
# Ignore points where both groups are 0% (not informative)
filter(pct + `Executive Time` > 0) %>%
# Pipe into ggplot
ggplot() +