-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcase_studies.qmd
1508 lines (1321 loc) · 45.5 KB
/
case_studies.qmd
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
---
execute:
message: false
warning: false
---
# Case studies {#sec-case-studies}
```{r}
#| echo: false
library(knitr)
knit_print.gt <- function(x, ...) {
# Two steps to avoid most Quarto changes of my table styles:
# 1. as_raw_html() to use table styles *inline*
# 2. wrap output in a div that resets all Quarto styles
stringr::str_c(
"<div style='all:initial';>\n",
gt::as_raw_html(x),
"\n</div>"
) |>
knitr::asis_output()
}
registerS3method(
"knit_print", 'gt_tbl', knit_print.gt,
envir = asNamespace("gt")
# important to overwrite {gt}s knit_print
)
```
## Fitness pricing
In this chapter we're going to build this Fitness pricing table I found [online](https://codepen.io/supacode/pen/ExjbmgG).
It's not really a data table but it's a fun exercise to build this.
```{r}
#| echo: false
#| column: screen
library(tidyverse)
library(gt)
levels <- c('Standard', 'Popular', 'Golden', 'Ultimate')
prices <- c(15, 25, 35, 50)
names(prices) <- levels
features <- c('Beginner Classes', 'Training Overview', 'Personal Training', 'Olympic Weightlifting', 'Foundation Training')
dat <- tibble(
level = levels,
monthly_price = prices[levels],
features = list(features[1], features[1:2], features[1:3], features),
booking_link = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
) |>
unnest(features) |>
select(level, features)
level_colors <- c(
Standard = "#c40d53",
Popular = "#26559b",
Golden = "#f90",
Ultimate = "#0d833e"
)
tier_feature_table <- function(level) {
level_data <- dat |>
## We use !! here so that this filter actually filters
filter(level == !!level) |>
mutate(in_level = TRUE) |>
complete(
expand(dat, features),
fill = list(in_level = FALSE)
) |>
select(in_level, features) |>
arrange(features = fct_relevel(features, !!features)) |>
mutate(
in_level = ifelse(
in_level,
fontawesome::fa('check', fill = level_colors[level]) |> html(),
fontawesome::fa('xmark', fill = level_colors[level]) |> html()
)
)
level_data |>
gt() |>
fmt_markdown(columns = 'in_level') |>
cols_width(in_level ~ px(25), everything() ~ px(175)) |>
tab_options(
column_labels.hidden = TRUE,
table.font.names = 'Source Sans Pro',
table_body.border.top.style = 'none',
table.border.top.style = 'none',
table_body.border.bottom.style = 'none',
table.border.bottom.style = 'none',
table_body.hlines.style = 'none',
)
}
tables_tib <- tibble(
level = levels,
table = map_chr(levels, ~as_raw_html(tier_feature_table(.)))
) |>
pivot_wider(names_from = level, values_from = table)
price_tib <- tibble(
level = levels,
price = paste0('$<span style="font-size:40px;">', prices, '</span>/month')
) |>
pivot_wider(names_from = level, values_from = price)
style_url <- function(link, color) {
htmltools::a(
href = link,
"Book now",
style = glue::glue("border-radius: 5px;color: white;background-color: {color};border-radius: 5px;padding: 8px 20px;display: inline-block;text-decoration:none")
)
}
url_tib <- tibble(
level = levels,
level_colors = level_colors[level],
booking_link = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
) |>
mutate(
booking_link = map2(booking_link, level_colors, style_url),
booking_link = map_chr(booking_link, ~as.character(.x))
) |>
select(-level_colors) |>
pivot_wider(names_from = level, values_from = booking_link)
levels_text_size <- px(30)
unstyled_fitness_table <- bind_rows(price_tib, tables_tib, url_tib) |>
mutate(dummy1 = '', .after = 1) |>
mutate(dummy2 = '', .after = 3) |>
mutate(dummy3 = '', .after = 5) |>
gt(id = 'fitness-table') |>
fmt_markdown(columns = everything()) |>
cols_align(align = 'center') |>
cols_label(
dummy1 = '',
dummy2 = '',
dummy3 = ''
) |>
cols_width(
dummy1 ~ px(15),
dummy2 ~ px(15),
dummy3 ~ px(15)
) |>
tab_header(
title = 'Fitness Pricing Table'
) |>
tab_footnote(
footnote = 'Design/Inspiration: @supacode | {gt} Remake: @rappa753',
placement = 'right'
)
unstyled_fitness_table |>
tab_style(
style = list(
cell_fill(color = level_colors['Standard']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Standard', rows = 1),
cells_column_labels(column = 'Standard')
)
) |>
tab_style(
style = list(
cell_fill(color = level_colors['Popular']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Popular', rows = 1),
cells_column_labels(column = 'Popular')
)
) |>
tab_style(
style = list(
cell_fill(color = level_colors['Golden']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Golden', rows = 1),
cells_column_labels(column = 'Golden')
)
) |>
tab_style(
style = list(
cell_fill(color = level_colors['Ultimate']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Ultimate', rows = 1),
cells_column_labels(column = 'Ultimate')
)
) |>
tab_style(
style = cell_text(size = levels_text_size),
locations = cells_column_labels()
) |>
tab_style(
style = list(cell_fill(color = 'white')),
locations = list(
cells_body(columns = contains('dummy')),
cells_column_labels(columns = contains('dummy'))
)
) |>
tab_style(
style = cell_borders(sides = 'bottom', color = '#D3D3D3'),
locations = cells_body(rows = 3, columns = c(1, 3, 5, 7))
) |>
tab_options(
table_body.border.top.style = 'none',
table.border.top.style = 'none',
table_body.border.bottom.style = 'none',
table.border.bottom.style = 'none',
table_body.hlines.style = 'none',
table_body.vlines.style = 'solid',
column_labels.border.top.style = 'none',
column_labels.border.bottom.style = 'none',
column_labels.border.lr.style = 'solid', # not working, set in css
column_labels.border.lr.width = px(1),
column_labels.padding = px(1),
data_row.padding = px(2),
table.font.names = 'Source Sans Pro',
heading.title.font.size = px(45),
heading.padding = px(10),
heading.border.bottom.style = 'none'
) |>
opt_css(
'#fitness-table .gt_footnote {
text-align: right; padding-top: 5px;
}
#fitness-table .gt_title {
font-family:"Oleo Script";
}
#fitness-table .gt_col_heading {
border-left-style:solid;
border-right-style:solid;
}
#fitness-table thead, tbody, tfoot, tr, td, th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
#fitness-table a {
&:hover {
transform: translateY(-3px);
box-shadow: 0 5px 5px rgba(0, 0, 0, 0.4);
}
&:active {
box-shadow: inset 0 -3px 5px rgba(0, 0, 0, 0.4);
}
}
'
)
```
Notice that I've even added a little interactive element.
You can hover over the booking button.
And clicking it redirects you to a certain web page.
To get started, let us define the data we need.
```{r}
#| collapse: true
library(tidyverse)
library(gt)
levels <- c('Standard', 'Popular', 'Golden', 'Ultimate')
prices <- c(15, 25, 35, 50)
names(prices) <- levels
prices
features <- c('Beginner Classes', 'Training Overview', 'Personal Training', 'Olympic Weightlifting', 'Foundation Training')
dat <- tibble(
level = levels,
monthly_price = prices[levels],
features = list(features[1], features[1:2], features[1:3], features),
booking_link = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
) |>
unnest(features) |>
select(level, features)
dat
level_colors <- c(
Standard = "#c40d53",
Popular = "#26559b",
Golden = "#f90",
Ultimate = "#0d833e"
)
level_colors
```
### Feature tables
From this we can create a table for the features of a single tier, e.g. the "Popular" tier.
First, we need to create the data set for this.
To do so, we're going to proceed as follows:
1. Filter `dat` so that we have only the features of our current tier
2. Add a new column `in_level` and set it to true (since all the filtered features are in the tier)
3. Expand the tibble so that the other features are also present in the data set (with `in_level` false)
```{r}
level <- 'Popular'
dat |>
## We use !! here so that this filter actually filters
filter(level == !!level) |>
mutate(in_level = TRUE) |>
complete(
expand(dat, features),
fill = list(in_level = FALSE, level = 'Popular')
)
```
Next, we can throw away the `level` column and sort the rows by the features (which we saved in the vector `features`).
```{r}
level <- 'Popular'
dat |>
## We use !! here so that this filter actually filters
filter(level == !!level) |>
mutate(in_level = TRUE) |>
complete(
expand(dat, features),
fill = list(in_level = FALSE, level = 'Popular')
) |>
select(in_level, features) |>
arrange(features = fct_relevel(features, !!features))
```
Finally, we turn the column `in_level` into fontawesome icons.
The colors of these icons are taken from our vector `level_colors`.
```{r}
level_data <- dat |>
## We use !! here so that this filter actually filters
filter(level == !!level) |>
mutate(in_level = TRUE) |>
complete(
expand(dat, features),
fill = list(in_level = FALSE)
) |>
select(in_level, features) |>
arrange(features = fct_relevel(features, !!features)) |>
mutate(
in_level = ifelse(
in_level,
fontawesome::fa('check', fill = level_colors[level]) |> html(),
fontawesome::fa('xmark', fill = level_colors[level]) |> html()
)
)
level_data
```
Sweet.
Now we can turn this into a `{gt}` table.
We have to use `fmt_markdown()` on our `in_leel` column so that the icons are actually displayed as icons.
While we're at it, we can style the table a tiny bit.
This includes getting rid of the column labels.
```{r}
level_data |>
gt() |>
fmt_markdown(columns = 'in_level') |>
cols_width(in_level ~ px(25), everything() ~ px(175)) |>
tab_options(
column_labels.hidden = TRUE,
table.font.names = 'Source Sans Pro',
table_body.border.top.style = 'none',
table.border.top.style = 'none',
table_body.border.bottom.style = 'none',
table.border.bottom.style = 'none',
table_body.hlines.style = 'none',
)
```
Alright, this looks already pretty good.
We'll get rid of the grid lines once we have assembled the full table.
Of course, we have to create this table for all tiers.
So let's wrap this into a function.
```{r}
#| code-fold: true
tier_feature_table <- function(level) {
level_data <- dat |>
## We use !! here so that this filter actually filters
filter(level == !!level) |>
mutate(in_level = TRUE) |>
complete(
expand(dat, features),
fill = list(in_level = FALSE)
) |>
select(in_level, features) |>
arrange(features = fct_relevel(features, !!features)) |>
mutate(
in_level = ifelse(
in_level,
fontawesome::fa('check', fill = level_colors[level]) |> html(),
fontawesome::fa('xmark', fill = level_colors[level]) |> html()
)
)
level_data |>
gt() |>
fmt_markdown(columns = 'in_level') |>
cols_width(in_level ~ px(25), everything() ~ px(175)) |>
tab_options(
column_labels.hidden = TRUE,
table.font.names = 'Source Sans Pro',
table_body.border.top.style = 'none',
table.border.top.style = 'none',
table_body.border.bottom.style = 'none',
table.border.bottom.style = 'none',
table_body.hlines.style = 'none',
)
}
```
::: panel-tabset
#### Standard
```{r}
tier_feature_table('Standard')
```
#### Popular
```{r}
tier_feature_table('Popular')
```
#### Golden
```{r}
tier_feature_table('Golden')
```
#### Ultimate
```{r}
tier_feature_table('Ultimate')
```
:::
And we can save all tables as HTML in a tibble.
For such occasions, `{gt}` has the function `as_raw_html()`.
```{r}
tables_tib <- tibble(
level = levels,
table = map_chr(levels, ~as_raw_html(tier_feature_table(.)))
) |>
pivot_wider(names_from = level, values_from = table)
tables_tib
```
### Prices and links
We can create similar tibbles for our prices.
Really, this table contains only the HTML-text for the monthly price tag where the price is larger than the rest.
```{r}
price_tib <- tibble(
level = levels,
price = paste0('$<span style="font-size:40px;">', prices, '</span>/month')
) |>
pivot_wider(names_from = level, values_from = price)
price_tib
```
Next, we can create yet another similar tibble for our URLs.
For this, I use the `a()` function from `{htmltools}` here.
More precisely, I have wrapped `a()` into a function `style_url()` that turns a URL into a colored box.
```{r}
style_url <- function(link, color) {
htmltools::a(
href = link,
"Book now",
style = glue::glue("border-radius: 5px;color: white;background-color: {color};border-radius: 5px;padding: 8px 20px;display: inline-block;text-decoration:none")
)
}
url_tib <- tibble(
level = levels,
level_colors = level_colors[level],
booking_link = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
) |>
mutate(
booking_link = map2(booking_link, level_colors, style_url),
booking_link = map_chr(booking_link, ~as.character(.x))
) |>
select(-level_colors) |>
pivot_wider(names_from = level, values_from = booking_link)
url_tib
```
### Assembling the tables
Now we can put everything together.
And in order to get white space between the tiers, we insert a few empty dummy columns.
```{r}
#| column: screen
levels_text_size <- px(30)
unstyled_fitness_table <- bind_rows(price_tib, tables_tib, url_tib) |>
mutate(dummy1 = '', .after = 1) |>
mutate(dummy2 = '', .after = 3) |>
mutate(dummy3 = '', .after = 5) |>
gt(id = 'fitness_table') |>
fmt_markdown(columns = everything()) |>
cols_align(align = 'center') |>
cols_label(
dummy1 = '',
dummy2 = '',
dummy3 = ''
) |>
cols_width(
dummy1 ~ px(15),
dummy2 ~ px(15),
dummy3 ~ px(15)
) |>
tab_header(
title = 'Fitness Pricing Table'
) |>
tab_footnote(
footnote = 'Design/Inspiration: @supacode | {gt} Remake: @rappa753',
placement = 'right'
)
unstyled_fitness_table
```
And the rest is "just" a series of `tab_style()` calls plus `tab_options()` and a bit of custom CSS.
```{r unstyled_fitness_table}
#| column: screen
#| code-fold: true
unstyled_fitness_table |>
tab_style(
style = list(
cell_fill(color = level_colors['Standard']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Standard', rows = 1),
cells_column_labels(column = 'Standard')
)
) |>
tab_style(
style = list(
cell_fill(color = level_colors['Popular']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Popular', rows = 1),
cells_column_labels(column = 'Popular')
)
) |>
tab_style(
style = list(
cell_fill(color = level_colors['Golden']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Golden', rows = 1),
cells_column_labels(column = 'Golden')
)
) |>
tab_style(
style = list(
cell_fill(color = level_colors['Ultimate']),
cell_text(color = 'white', weight = 'bold')
),
locations = list(
cells_body(columns = 'Ultimate', rows = 1),
cells_column_labels(column = 'Ultimate')
)
) |>
tab_style(
style = cell_text(size = levels_text_size),
locations = cells_column_labels()
) |>
tab_style(
style = list(cell_fill(color = 'white')),
locations = list(
cells_body(columns = contains('dummy')),
cells_column_labels(columns = contains('dummy'))
)
) |>
tab_style(
style = cell_borders(sides = 'bottom', color = '#D3D3D3'),
locations = cells_body(rows = 3, columns = c(1, 3, 5, 7))
) |>
tab_options(
table_body.border.top.style = 'none',
table.border.top.style = 'none',
table_body.border.bottom.style = 'none',
table.border.bottom.style = 'none',
table_body.hlines.style = 'none',
table_body.vlines.style = 'solid',
column_labels.border.top.style = 'none',
column_labels.border.bottom.style = 'none',
column_labels.border.lr.style = 'solid', # not working, set in css
column_labels.border.lr.width = px(1),
column_labels.padding = px(1),
data_row.padding = px(2),
table.font.names = 'Source Sans Pro',
heading.title.font.size = px(45),
heading.padding = px(10),
heading.border.bottom.style = 'none'
) |>
opt_css(
'#fitness_table .gt_footnote {
text-align: right; padding-top: 5px;
}
#fitness_table .gt_title {
font-family:"Oleo Script";
}
#fitness_table .gt_col_heading {
border-left-style:solid;
border-right-style:solid;
}
#fitness_table thead, tbody, tfoot, tr, td, th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
#fitness_table a {
&:hover {
transform: translateY(-3px);
box-shadow: 0 5px 5px rgba(0, 0, 0, 0.4);
}
&:active {
box-shadow: inset 0 -3px 5px rgba(0, 0, 0, 0.4);
}
}
'
)
```
## NYT bestseller
This one is a recreation of an awesome table [Tanya Shapiro](https://twitter.com/tanya_shapiro/status/1584616721251725312) made with `{ggplot2}`.
It is a huge table, so you'll probably need to look at this on a large screen.
But just to be safe.
Here's a [screenshot of the table](img/screenshot_table.png) as well.
```{r}
#| column: screen
#| echo: false
library(tidyverse)
library(gt)
library(gtExtras)
find_best_book <- function(decade, author) {
best_books <- nyt_dat |>
filter(decade == !!decade, author == !!author) |>
count(title, sort = TRUE)
best_books[[1, 'title']] |> str_to_title()
}
find_number_of_weeks_per_year <- function(decade, author){
nyt_dat |>
filter(decade == !!decade, author == !!author) |>
count(year, name = 'weeks') |>
complete(tibble(year = decade:(decade + 9)), fill = list(weeks = 0)) |>
arrange(year) |>
pull(weeks)
}
map2color<-function(x, pal = rev(RColorBrewer::brewer.pal(11, 'Spectral')), limits=NULL){
if(is.null(limits)) limits <- range(x)
pal[findInterval(x,seq(limits[1],limits[2],length.out=length(pal)+1), all.inside=TRUE)]
}
create_point_div <- function(color, size) {
glue::glue(
'<span style="height: {size}em;width: {size}em;background-color: {color};border-radius: 50%;margin-top:4px;display:inline-block;margin-left:2px;"></span>'
)
}
format_text <- function(weeks, author, best_book, colors) {
glue::glue(
'<span style = "color:white;font-weight:lighter;font-size:12pt;">{str_to_upper(weeks)} WEEKS ON THE LIST</span> {create_point_div(colors, 0.75)}',
'<br>',
'<span style = "color:white;font-weight:bold;font-size:22pt;">{author}</span>',
'<br>',
'<span style = "color:white;font-size:12pt;">{best_book}</span>'
)
}
nyt_dat <- readr::read_tsv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-05-10/nyt_full.tsv') |>
mutate(decade = (year %/% 10) * 10)
top5_authors_by_decade <- nyt_dat |>
filter(between(year, 1960, 2019)) |>
count(author, decade, sort = T, name = 'weeks') |>
group_by(decade) |>
slice_max(weeks, n = 5) |>
ungroup()
top5_authors_and_book_by_decade <- top5_authors_by_decade |>
mutate(
best_book = map2_chr(decade, author, find_best_book),
sparkline_weeks = map2(decade, author, find_number_of_weeks_per_year)
)
image_links <- tibble(
author = top5_authors_and_book_by_decade |> pull(author) |> unique(),
img = c(
'https://images.gr-assets.com/authors/1327446818p8/77616.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/John_O%27Hara_cph.3b08576.jpg/1024px-John_O%27Hara_cph.3b08576.jpg',
'https://upload.wikimedia.org/wikipedia/commons/8/88/Taylor_caldwell_a.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Irving_Wallace%2C_1972.jpg/330px-Irving_Wallace%2C_1972.jpg',
'https://upload.wikimedia.org/wikipedia/commons/d/d6/Leon_Uris_%28cropped%29.jpg',
'https://images-na.ssl-images-amazon.com/images/I/41RMdx8BJHL.__01_SX120_CR0,0,120,120__.jpg',
'https://upload.wikimedia.org/wikipedia/en/a/a2/Robert_Ludlum_%281927-2001%29.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Herman_Wouk_%28cropped%29.jpg/330px-Herman_Wouk_%28cropped%29.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Agatha_Christie.png/330px-Agatha_Christie.png',
'https://upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Frederick_Forsyth_-_01.jpg/375px-Frederick_Forsyth_-_01.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Stephen_King%2C_Comicon.jpg/330px-Stephen_King%2C_Comicon.jpg',
'https://images1.penguinrandomhouse.com/author/29599',
'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/James_Albert_Michener_%C2%B7_DN-SC-92-05368.JPEG/330px-James_Albert_Michener_%C2%B7_DN-SC-92-05368.JPEG',
'https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Tom_Clancy_at_Burns_Library_cropped.jpg/330px-Tom_Clancy_at_Burns_Library_cropped.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/5/5f/Grisham_John_by_C_Harrison_.jpg/300px-Grisham_John_by_C_Harrison_.jpg',
'https://upload.wikimedia.org/wikipedia/en/7/70/Robert_James_Waller.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Mary_Higgins_Clark_at_the_Mazza_Museum.jpg/330px-Mary_Higgins_Clark_at_the_Mazza_Museum.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dan_Brown_bookjacket_cropped.jpg/330px-Dan_Brown_bookjacket_cropped.jpg',
'https://upload.wikimedia.org/wikipedia/commons/1/1d/James_Patterson.jpg',
'https://upload.wikimedia.org/wikipedia/commons/a/af/Nicholas-Sparks-Autograph-1-4-06.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/David_Baldacci_-_2015_National_Book_Festival_%286%29.jpg/330px-David_Baldacci_-_2015_National_Book_Festival_%286%29.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Anthony_Doerr_%282015%29.jpg/330px-Anthony_Doerr_%282015%29.jpg'
)
)
full_dat <- top5_authors_and_book_by_decade |>
left_join(image_links)
# can be higher than 52 bc of multiple books
highest_week_count_per_year <- full_dat |>
pull(sparkline_weeks) |>
map_dbl(max) |>
max()
create_sparkline <- function(sparkline) {
ggplot() +
geom_line(
mapping = aes(x = seq_along(sparkline), y = sparkline),
color = 'white',
linewidth = 3
) +
annotate(
'text',
x = c(1, 10),
y = sparkline[c(1, 10)],
label = sparkline[c(1, 10)],
color = 'white',
hjust = c(1.2, -0.2),
size = 16
) +
coord_cartesian(xlim = c(-5, 15), ylim = c(-5, highest_week_count_per_year)) +
theme_void() +
theme(plot.background = element_rect(fill = 'black'))
}
create_decade_table <- function(decade, img_size = 75) {
full_dat |>
mutate(color = map2color(weeks)) |>
filter(decade == !!decade) |>
mutate(
author = if_else(author == 'Robert James Waller', 'Robert Waller', author),
rank = 1:5,
decade = paste0(decade, 's'),
joined_text = pmap(.l = list(weeks, author, best_book, color), format_text)
) |>
select(
rank, decade, joined_text, sparkline_weeks, img
) |>
gt(groupname_col = 'decade') |>
gt_img_circle(column = 'img', height = img_size) |>
text_transform(
locations = cells_body(columns = sparkline_weeks),
fn = function(column) {
map(column, ~c(str_split_1(., pattern = ', '))) |>
map(parse_number) |>
map(create_sparkline) |>
ggplot_image(height = 75)
}
) |>
cols_width(
img ~ px(82), # needs to be a little more than 75px
joined_text ~ px(300),
sparkline_weeks ~ px(100)
) |>
cols_align('left', columns = 'joined_text') |>
fmt_markdown(columns = c('joined_text')) |>
tab_style(
style = cell_text(size = '15pt', weight = 'bold', v_align = 'top'),
locations = cells_body('rank')
) |>
tab_style(
locations = cells_row_groups(),
style = cell_text(align = 'center')
) |>
tab_options(
table.background.color = 'black',
table.font.color = 'white',
table.font.names = 'Open Sans',
column_labels.hidden = TRUE,
row_group.border.top.style = 'none',
row_group.border.bottom.style = 'none',
table.border.bottom.style = 'solid',
table.border.bottom.width = px(1),
table.border.top.style = 'none',
table_body.border.bottom.style = 'none',
table_body.border.top.style = 'none',
heading.border.bottom.style = 'none',
column_labels.border.top.style = 'none',
)
}
# Create tables for each decade and convert them to HTML
raw_tables <- map(seq(1960, 2010, 10), create_decade_table) |>
map_chr(as_raw_html)
title <- paste0(
"<span style='font-family:Chomsky;font-size:42pt;color:white;'> The New York Times</span>",
"<span style='font-family:opensans;font-size:24pt;color:white;'> **Best Selling Authors**</span>",
"<br><span style='font-family:opensans;font-size:18pt;color:#D6D6D6'>Top authors by decade. Ranking based on number of weeks author appeared on list. Sparkline depicts total weeks<br>by year (counts multiple books). Top performing book included beneath each author's name. Data from Post45 Data Collective.</span><br>"
)
tbl <- tibble(
col1 = raw_tables[c(1, 4)],
col2 = raw_tables[c(2, 5)],
col3 = raw_tables[c(3, 6)]
) |>
gt(id = 'my_tbl') |>
fmt_markdown(columns = everything()) |>
tab_header(
title = md(title)
) |>
tab_footnote(
html(glue::glue(
'{ggplot2} Original: <<fontawesome::fa("twitter")>>@tanya_shapiro |
{gt} recreation: <<fontawesome::fa("twitter")>>@rappa753',
.open = "<<", .close = ">>"
))
) |>
cols_width(
col1 ~ px(600),
col2 ~ px(600),
col3 ~ px(600)
) |>
tab_style(
locations = cells_body(rows = 1),
style = cell_borders(style = 'hidden')
) |>
tab_options(
table.background.color = 'black',
table.font.color = 'white',
table.font.names = 'Open Sans',
column_labels.hidden = TRUE,
row_group.border.top.style = 'none',
row_group.border.bottom.style = 'none',
table.border.bottom.style = 'solid',
table.border.bottom.width = px(1),
table.border.top.style = 'none',
table_body.border.bottom.style = 'none',
table_body.border.top.style = 'none',
heading.border.bottom.style = 'none',
column_labels.border.top.style = 'none',
) |>
opt_css(
'#my_tbl .gt_footnote {
text-align: right;
padding-top: 20px;
padding-bottom:5px;
font-family:"Open Sans";
font-size:10pt;
font-weight:bold;
}
#my_tbl .gt_row {
border-top-color: grey;
border-bottom-color: grey;
}
#my_tbl thead, tbody, tfoot, tr, td, th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
div#my_tbl {line-height:1.1;}
'
)
tbl
```
### Data Preparation
The first thing we need to do is get the data.
This requires a bit of data wrangling on the underlying [TidyTuesdaty data set](https://github.com/rfordatascience/tidytuesday/blob/master/data/2022/2022-05-10/readme.md).
The following code finds the top 5 authors by decade, their best book and the data for the sparkline plot.
```{r}
# Book finder helper function
find_best_book <- function(decade, author) {
best_books <- nyt_dat |>
filter(decade == !!decade, author == !!author) |>
count(title, sort = TRUE)
best_books[[1, 'title']] |> str_to_title()
}
# Sparkline helper function
find_number_of_weeks_per_year <- function(decade, author){
nyt_dat |>
filter(decade == !!decade, author == !!author) |>
count(year, name = 'weeks') |>
complete(tibble(year = decade:(decade + 9)), fill = list(weeks = 0)) |>
arrange(year) |>
pull(weeks)
}
# Data from the TidyTuesday repo
nyt_dat <- readr::read_tsv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-05-10/nyt_full.tsv') |>
mutate(decade = (year %/% 10) * 10)
# Find top 5 authors
top5_authors_by_decade <- nyt_dat |>
filter(between(year, 1960, 2019)) |>
count(author, decade, sort = T, name = 'weeks') |>
group_by(decade) |>
slice_max(weeks, n = 5) |>
ungroup()
# Find their best book and the info for the sparlines
top5_authors_and_book_by_decade <- top5_authors_by_decade |>
mutate(
best_book = map2_chr(decade, author, find_best_book),
sparkline_weeks = map2(decade, author, find_number_of_weeks_per_year)
)
top5_authors_and_book_by_decade
```
Next, we find images of the authors online and save them in a tibble `image_links`.
This tibble can then be joined with `top5_authors_and_book_by_decade`.
```{r}
image_links <- tibble(
author = top5_authors_and_book_by_decade |> pull(author) |> unique(),
img = c(
'https://images.gr-assets.com/authors/1327446818p8/77616.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/John_O%27Hara_cph.3b08576.jpg/1024px-John_O%27Hara_cph.3b08576.jpg',
'https://upload.wikimedia.org/wikipedia/commons/8/88/Taylor_caldwell_a.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Irving_Wallace%2C_1972.jpg/330px-Irving_Wallace%2C_1972.jpg',
'https://upload.wikimedia.org/wikipedia/commons/d/d6/Leon_Uris_%28cropped%29.jpg',
'https://images-na.ssl-images-amazon.com/images/I/41RMdx8BJHL.__01_SX120_CR0,0,120,120__.jpg',
'https://upload.wikimedia.org/wikipedia/en/a/a2/Robert_Ludlum_%281927-2001%29.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Herman_Wouk_%28cropped%29.jpg/330px-Herman_Wouk_%28cropped%29.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Agatha_Christie.png/330px-Agatha_Christie.png',
'https://upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Frederick_Forsyth_-_01.jpg/375px-Frederick_Forsyth_-_01.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Stephen_King%2C_Comicon.jpg/330px-Stephen_King%2C_Comicon.jpg',
'https://images1.penguinrandomhouse.com/author/29599',
'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/James_Albert_Michener_%C2%B7_DN-SC-92-05368.JPEG/330px-James_Albert_Michener_%C2%B7_DN-SC-92-05368.JPEG',
'https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Tom_Clancy_at_Burns_Library_cropped.jpg/330px-Tom_Clancy_at_Burns_Library_cropped.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/5/5f/Grisham_John_by_C_Harrison_.jpg/300px-Grisham_John_by_C_Harrison_.jpg',
'https://upload.wikimedia.org/wikipedia/en/7/70/Robert_James_Waller.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Mary_Higgins_Clark_at_the_Mazza_Museum.jpg/330px-Mary_Higgins_Clark_at_the_Mazza_Museum.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dan_Brown_bookjacket_cropped.jpg/330px-Dan_Brown_bookjacket_cropped.jpg',
'https://upload.wikimedia.org/wikipedia/commons/1/1d/James_Patterson.jpg',
'https://upload.wikimedia.org/wikipedia/commons/a/af/Nicholas-Sparks-Autograph-1-4-06.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/David_Baldacci_-_2015_National_Book_Festival_%286%29.jpg/330px-David_Baldacci_-_2015_National_Book_Festival_%286%29.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Anthony_Doerr_%282015%29.jpg/330px-Anthony_Doerr_%282015%29.jpg'