-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path06-visualization.qmd
1807 lines (1464 loc) · 55.5 KB
/
06-visualization.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
---
title: "Modelling and visualizing data"
---
```{r, include=FALSE}
library(tidyverse)
library(plotly)
library(leaflet)
library(htmltools)
library(listviewer)
library(htmlwidgets)
library(haven)
ess <- readRDS("data/ess_trust.rds")
ess_geo <- readRDS("data/ess_trust_geo.rds")
```
You will learn how to:
- Implement and customize interactivity in plots
- Leverage input events to fine-tune visualizations
- Use proxies to update plots and maps on-the-fly (appendix)
- Turn simple R plots into powerful Swiss knifes
## Interactive visualization: The core of Shiny
- Shiny offers the perfect basis for visualization
- Plots can be modified using UI inputs
- Seamless integration of interactivity elements (e.g. pan, zoom)
- Dashboards facilitate the idea of story-telling by providing context to plots
### Good practice examples
- Examples of these concepts can be seen in many Shiny apps, one example is Edward Parker's [COVID-19 tracker](https://vac-lshtm.shinyapps.io/ncov_tracker/)
::: callout-note
#### Question
Explore the COVID-19 tracker. Do you think this is a good Shiny app? If so, why? If not, why not?
:::

### Plain plotting vs. Shiny
+---------------+--------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------------------------------------------------------------+
| Feature | Plain R | Shiny | Examples |
+===============+======================================================================================+==========================================================================================+============================================================================+
| Reactivity | Changes in the visualization have to be changed in the code | Visualizations can be modified on the fly using widgets like drop-down menus | [ExPanD](https://jgassen.shinyapps.io/expand_fuel_economy/) |
+---------------+--------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------------------------------------------------------------+
| Interactivity | Plots are static raster or vector images | Plots can be dynamic and can be interacted with | [COVID-19 tracker](https://vac-lshtm.shinyapps.io/ncov_tracker/) |
+---------------+--------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------------------------------------------------------------+
| Narrativity | Sense-making happens through manual annotation, e.g. in an article or a presentation | Plots are embedded in a compilation of narrative elements that can tell a coherent story | [Freedom of Press Shiny app](https://johncoene.shinyapps.io/fopi-contest/) |
| | | | |
| | | | [GRETA Analytics](https://projectgreta.shinyapps.io/greta-analytics/) |
+---------------+--------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------------------------------------------------------------+
| Medium | Reactivity | Interactivity | Narrativity |
|--------------------------|------------|---------------|-------------|
| Plain image | ❌ | ❌ | ❌ |
| Paper / report | ❌ | ❌ | ✅ |
| Dashboard (e.g. Tableau) | ❌ | ☑️ | ✅ |
| Quarto / RMarkdown | ❌ | ☑️ | ✅ |
| Traditional website | ☑️ | ✅ | ✅ |
| Shiny | ✅ | ✅ | ✅ |
### Current app state
- In the last sections, we added a table and a plot and linked them to a number of inputs
- The code chunk below contains the current app state
- In this section, we will:
- Augment the violin plot
- Add an interactive map
```{r test, eval=FALSE, file="shinyapps/example/06-base.R"}
#| code-fold: true
#| code-summary: Full code for the current app state
```
### Recap: Plotting in Shiny
- Inserting plots in Shiny apps works just like any other UI component
- You need two things: `plotOutput()` (or similar) in the UI and `renderPlot()` (or similar) in the server function
- [`plotOutput()`](https://shiny.posit.co/r/reference/shiny/1.7.4/plotoutput) creates the empty element in the UI where the plot will go
- [`renderPlot()`](https://shiny.posit.co/r/reference/shiny/1.7.4/renderplot) renders the plot and updates the UI element every time a reactive dependency is invalidated
## Data masking
- Data masking means that function arguments are not evaluated traditionally, but captured or "defused" for later use
- This strategy is employed by many functions for plotting or creating tables including the tidyverse (also called "tidy evaluation")
- In a practical sense, this means you can specify string values such as column names as you would variables
- To learn more about data masking in Shiny, see [chapter 20](https://adv-r.hadley.nz/evaluation.html) of Advanced R and [chapter 12](https://mastering-shiny.org/action-tidy.html#action-tidy) of Mastering Shiny
```{r, eval=FALSE}
# NSE as "tidy evaluation"
ess %>%
summarize(mean = mean(trust_eu))
# NSE in base R
subset(ess, select = trust_eu)
with(ess, sum(trust_eu))
```
### Why is data masking a problem?
- Data masks are a little tricky to handle in higher levels of abstraction, i.e. functions or reactive expressions
- In such cases, we do not need one specific variable, but a dynamically changing variable
```{r, error=TRUE}
plot_df <- function(df, var) {
ggplot(df) +
aes(x = var) +
geom_histogram()
}
plot_df(ess, "trust_eu")
```
### Strategy 1: Use tidy pronouns
- Tidyverse functions that feature tidy evaluation support the `.data` and `.env` pronouns
- The `.data` pronoun is a representation of the original data which can be used in a masked environment
- See also the [reference](https://rlang.r-lib.org/reference/dot-data.html) of `rlang`
```{r, eval=FALSE}
plot_df <- function(df, var) {
ggplot(df) +
aes(x = .data[[var]]) +
geom_histogram()
}
plot_df(ess, "trust_eu")
```
### Strategy 2: Convert strings to expressions
- Sometimes, masked expressions can simply be constructed as strings
- One example are formulas (e.g. in `lm(y ~ x1 + x2)`)
- The `as.formula` function can create formula objects manually
```{r, eval=FALSE}
linreg <- function(df, y, x) {
fm <- paste(y, "~", paste(x, collapse = " + "))
fm <- as.formula(fm)
lm(fm, data = df)
}
linreg(ess, y = "trust_eu", x = c("age", "left_right"))
```
### Strategy 3: Change names
- In case of poorly implemented data masking, no tools are available to inject variables
- One strategy to overcome such situations could be to simply change the object names
```{r, eval=FALSE}
plot_df <- function(df, var) {
df <- df[, var]
names(df) <- "x"
ggplot(df) +
aes(x = x) +
geom_histogram()
}
plot_df(ess, "trust_eu")
```
## Interactivity
- R itself is *very bad* at interactivity
- Shiny supports some very essential interactivity through `plotOutput`
- Not covered in this workshop! For a primer, check out [chapter 7.1](https://mastering-shiny.org/action-graphics.html#interactivity) of Mastering Shiny
- All of today's cool kids use interactivity through Javascript interfaces
- Shiny can generally process all kinds of Javascript-based widgets because Shiny apps are HTML documents
### Popular Javascript interfaces
- Examples of Javascript libraries and their corresponding R packages
- [Plotly](https://plotly-r.com/) (covered here)
- [Leaflet](https://rstudio.github.io/leaflet/) (covered here)
- [Highcharts](https://jkunst.com/highcharter/)
- [Bokeh](https://hafen.github.io/rbokeh/index.html)
- [D3](https://rstudio.github.io/r2d3/index.html)
- [Apache ECharts](https://echarts4r.john-coene.com/)
- [Frappe Charts](https://merlinoa.github.io/rfrappe/)
- [billboard.js](https://dreamrs.github.io/billboarder/)
- [apexcharts.js](https://dreamrs.github.io/apexcharter/)
- [Google Charts](https://mages.github.io/googleVis/)
- [amCharts 4](https://doi.org/10.32614/CRAN.package.rAmCharts4)
- [Deck.gl](https://symbolixau.github.io/mapdeck/articles/mapdeck.html)
- [WebGL](https://dmurdoch.github.io/rgl/index.html)
## Plotly
- Plotly is an open-source library to create charts that can be interacted with in various way
- It supports several languages including R and Python
- Plotly is arguably the most renowned R package for interactive plotting
- It even motivated an entire book: <https://plotly-r.com/>
### Plotly's grammar of graphics
- Similar to ggplot2, R plotly defines its own grammar of graphics
- A plotly canvas is created with `plot_ly()`
- Additional plot elements can be added through pipes `%>%` or `|>`
```{r}
ess_geo <- readRDS("data/ess_trust_geo.rds")
ess_geo <- mutate(
ess_geo,
region = case_match(
country,
c("AT", "BE", "CH", "DE", "NL", "PL", "CZ") ~ "Central",
c("BG", "EE", "HR", "HU", "LT", "LV", "PL", "SI", "SK") ~ "Eastern",
c("ES", "IT", "PT", "RS", "ME") ~ "Southern",
c("IS", "SE", "FI", "GB", "IE", "DK") ~ "Northern"
)
)
plot_ly(
sf::st_drop_geometry(ess_geo),
x = ~trust_eu, # <1>
y = ~left_right, # <1>
z = ~age, # <1>
color = ~region, # <1>
text = ~country # <1>
) %>%
add_markers() %>% # <2>
layout(scene = list( # <3>
xaxis = list(title = 'Trust in the EU'), # <3>
yaxis = list(title = 'Left-right placement'), # <3>
zaxis = list(title = 'Age') # <3>
)) # <3>
```
1. Variables such as x, y, z and color are defined as formulas in a call to `plot_ly`. This is comparable to calling `ggplot(aes(x, y, z, color))`.
2. The plot type is added through a pipe. This is comparable to `ggplot2` functions such as `geom_point` or `geom_bar`.
3. Visual sugar is then added by calling `layout` and manually editing the axis titles.
### Quick and dirty interactivity
- One important advantage of plotly is that you do not need to learn its grammar
- `ggplot2` plots can very easily be converted to an interactive plotly plot:
```{r}
p <- ggplot(iris) +
geom_point(aes(Sepal.Width, Sepal.Length))
p
```
```{r}
ggplotly(p)
```
### Extending plotly
#### Customization
- We can extend Plotly objects using three functions:
- `layout()` changes the plot organisation (think [`ggplot2::theme()`](https://ggplot2.tidyverse.org/reference/theme.html)), e.g.:
- colors, sizes, fonts, positions, titles, ratios and alignment of all kinds of plot elements
- `updatemenus` adds buttons or drop down menus that can change the plot style or layout (see [here](https://plotly.com/r/dropdowns/) for examples)
- `sliders` adds sliders that can be useful for time series (see [here](https://plotly.com/r/sliders/) for examples)
- `config()` changes interactivity configurations, e.g.:
- The `modeBarButtons` options and `displaylogo` control the buttons in the mode bar
- `toImageButtonOptions` controls the format of plot downloads
- `scrollZoom` enables or disables zooming by scrolling
- `style()` changes data-level attributes (think [`ggplot2::scale_`](https://ggplot2.tidyverse.org/reference/#scales)), e.g.:
- `hoverinfo` controls whether tooltips are shown on hover
- `mode` controls whether to show points, lines and/or text in a scatter plot
- `hovertext` modifies the tooltips texts shown on hover
#### Schema
- The actual number of options is immense!
- You can explore all options by calling [`plotly::schema()`](https://rdrr.io/cran/plotly/man/schema.html)
```{r eval=FALSE}
schema()
```
```{r echo=FALSE}
sch <- jsonedit(plotly:::Schema, mode = "form")
path <- file.path(getwd(), "schema.html")
saveWidget(sch, path)
tags$iframe(srcdoc = paste(readLines(path), collapse = '\n'), width = "100%", height = 500)
```
```{r echo=FALSE}
unlink(path)
```
#### Example
```{r}
p <- ggplot(iris) +
geom_point(aes(Sepal.Width, Sepal.Length))
ggplotly(p) %>%
config(
modeBarButtonsToRemove = c( # <1>
"sendDataToCloud", "zoom2d", "select2d", "lasso2d", "autoScale2d", # <1>
"hoverClosestCartesian", "hoverCompareCartesian", "resetScale2d" # <1>
), # <1>
displaylogo = FALSE, # <2>
toImageButtonOptions = list( # <3>
format = "svg", # <3>
filename = "plot", # <3>
height = NULL, # <3>
width = NULL # <3>
), # <3>
scrollZoom = TRUE # <4>
)
```
1. Removes specified buttons from the modebar.
2. Removes the Plotly logo.
3. Changes the output of snapshots taken of the plot. Setting `height` and `width` to `NULL` keeps the aspect ratio of the plot as it is shown in the app.
4. Enables zooming through scrolling.
### Plotly and Shiny
- Since plotly does not produce static plots like `ggplot2`, it cannot be served by `plotOutput` and `renderPlot`
- Plotly defines two new functions:
- `plotlyOutput` on the UI side
- `renderPlotly` on the server side
UI:
```{r, eval=FALSE}
#| source-line-numbers: "17"
mainPanel(
tabsetPanel(
type = "tabs",
### Table tab ----
tabPanel(
title = "Table",
div(
style = "height: 600px; overflow-y: auto;",
tableOutput("table")
)
),
### Plot tab ----
tabPanel(
title = "Plot",
plotlyOutput("plot", height = 600)
)
)
)
```
Server:
```{r, eval=FALSE}
#| source-line-numbers: "8,12"
output$plot <- renderPlotly({
xvar <- input$xvar
yvar <- input$yvar
plot_data <- filtered() %>%
drop_na() %>%
mutate(across(where(is.numeric), .fns = as.ordered))
p <- ggplot(plot_data) +
aes(x = .data[[xvar]], y = .data[[yvar]], group = .data[[xvar]]) +
geom_violin(fill = "lightblue", show.legend = FALSE) +
theme_classic()
ggplotly(p)
})
```
```{r, eval=FALSE, file="shinyapps/example/06-plotly.R"}
#| code-fold: true
#| code-summary: "Complete code (important lines are highlighted)"
#| source-line-numbers: "83,146,150"
```
## Leaflet
- Leaflet is an open-source JavaScript library to create interactive maps
- Like plotly it is one of the most popular applications for interactive mapping
- The [leaflet](https://rstudio.github.io/leaflet/index.html) package makes it easy to create interactive maps directly in R
- Leaflet is very light-weight! This is good, but it's also bad because it means extra work.
### Leaflet's grammar of graphics
- Just like `ggplot2` and `plotly`, leaflet is inspired by a grammar of graphics
- A map canvas can be created using the `leaflet()` function
- Additional elements are added through pipes `%>%` or `|>`
- Palettes are created using the `leaflet::color` function family
```{r}
leaflet(ess_geo) %>% # <1>
addTiles() %>% # <2>
addPolygons( # <3>
weight = 2, # <3>
opacity = 1, # <3>
fillOpacity = 0.7 # <3>
) # <4>
```
1. Leaflet supports four types of palettes: Bin, Quantile, Factor, and Numeric. In this case we have a numeric variable.
2. `leaflet()` is the powerhorse of the `leaflet` package. It is comparable to `ggplot()` or `plot_ly()`.
3. `addTiles()` adds a background map.
4. `addPolygons()` adds polygons to the map. This function accepts several visual arguments to control, for example, the line width and opacity.
### Adding data
- To add colorized data, we must first define how to color this data
- Leaflet defines four color functions to create a palette:
- Numeric
- Bin
- Quantile
- Factor
- Depending on the data
```{r}
#| source-line-numbers: "2,7"
pal <- colorNumeric("YlOrRd", domain = NULL) # <1>
leaflet(ess_geo) %>%
addTiles() %>%
addPolygons(
fillColor = pal(ess_geo[["trust_eu"]]), # <2>
weight = 2,
opacity = 1,
color = "white",
fillOpacity = 0.7
)
```
1. Define a numeric palette with a gradient Yellow-Orange-Red
2. Apply this palette to the data to generate color values
### Adding a legend
- Just like adding data, adding legends has to be done manually
- The `addLegend()` function
```{r}
#| source-line-numbers: "12-18"
pal <- colorNumeric("YlOrRd", domain = NULL)
leaflet(ess_geo) %>%
addTiles() %>%
addPolygons(
fillColor = pal(ess_geo[["trust_eu"]]),
weight = 2,
opacity = 1,
color = "white",
fillOpacity = 0.7
) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = ess_geo[["trust_eu"]],
opacity = 0.7,
title = "Trust in the EU"
)
```
### Adding interactivity
- Right now, the leaflet map cannot be interacted with
- Interactivity has to be added manually
- Two new features:
- `highlightOptions` adds a highlight effect when hovering over a polygon
- `labels` adds labels that appear when hovering over a polygon
- Caveats:
- Labels have to be formatted manually, as per usual
- Beautifully styled labels require some knowledge of HTML and CSS
```{r}
#| source-line-numbers: "2-7,20-27"
labels <- sprintf( # <1>
"<strong>%s</strong><br>%s", # <1>
ess_geo$country, # <1>
ess_geo$trust_eu # <1>
) # <1>
labels <- lapply(labels, HTML) # <2>
pal <- colorNumeric("YlOrRd", domain = NULL)
leaflet(ess_geo) %>%
addTiles() %>%
addPolygons(
fillColor = pal(ess_geo[["trust_eu"]]),
weight = 2,
opacity = 1,
color = "white",
fillOpacity = 0.7,
highlightOptions = highlightOptions( # <3>
weight = 2, # <3>
color = "#666", # <3>
fillOpacity = 0.7, # <3>
bringToFront = TRUE # <3>
), # <3>
label = labels # <3>
) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = ess_geo[["trust_eu"]],
opacity = 0.7,
title = "Trust in the EU"
)
```
1. Labels need to be created manually. Here, I generate very essential labels containing the country in bold and the trust value below it.
2. Labels must be explicitly classified as HTML code. This can be done using the `shiny::HTML` function.
3. Interactivity is then simply added through the `label` and `highlightOptions` arguments to `addPolygons()`.
### Leaflet and Shiny
- Again, Leaflet does not produce static plots and thus cannot be served by `plotOutput` and `renderPlot`
- The `leaflet` package defines two functions:
- `leafletOutput` to create the canvas in the UI
- `renderLeaflet` to render the Leaflet widget in the server function
UI:
```{r, eval=FALSE}
#| source-line-numbers: "21-24"
mainPanel(
tabsetPanel(
type = "tabs",
### Table tab ----
tabPanel(
title = "Table",
div(
style = "height: 600px; overflow-y: auto;",
tableOutput("table")
)
),
### Plot tab ----
tabPanel(
title = "Plot",
plotlyOutput("plot", height = 600)
),
### Map tab ----
tabPanel(
title = "Map",
leafletOutput("map", height = 600)
)
)
)
```
Server:
```{r, eval=FALSE}
output$map <- renderLeaflet({
var <- input$xvar
plot_data <- ess_geo[c("country", var)]
# create labels with a bold title and a body
labels <- sprintf(
"<strong>%s</strong><br>%s",
plot_data$country,
plot_data[[var]]
)
labels <- lapply(labels, HTML)
# create a palette for numerics and ordinals
if (is.ordered(plot_data[[var]])) {
pal <- colorFactor("YlOrRd", domain = NULL)
} else {
pal <- colorNumeric("YlOrRd", domain = NULL)
}
# construct leaflet canvas
leaflet(plot_data) %>%
# add base map
addTiles() %>%
# add choropleths
addPolygons(
fillColor = pal(plot_data[[var]]),
weight = 2,
opacity = 1,
color = "white",
fillOpacity = 0.7,
# highlight polygons on hover
highlightOptions = highlightOptions(
weight = 2,
color = "#666",
fillOpacity = 0.7,
bringToFront = TRUE
),
label = labels
) %>%
# add a legend
addLegend(
position = "bottomleft",
pal = pal,
values = plot_data[[var]],
opacity = 0.7,
title = var
)
})
```
```{r, eval=FALSE, file="shinyapps/example/06-leaflet.R"}
#| code-fold: true
#| code-summary: "Complete code (important lines are highlighted)"
#| source-line-numbers: "86-90,153-201"
```
## Appendix: Reactivity
- We already covered Shiny's reactivity quite extensively
- Recall:
- A user changes an input
- The server processes that input
- The UI updates
- It turns out, most plotting systems in Shiny support what we will call "plot events"
### Plot events
- A plot event is triggered by a widget if a user interacts with it
- In a sense, plot events are a cross-over of interactivity and reactivity
- A plot event is hidden, i.e. it does not have to be explicitly defined in the UI -- it's just created automatically on the go.
- By far not all widgets define plot events, but the most important plotting frameworks do:
- `plotly` defines a plethora of plot events through the `event_data` function
- `leaflet` automatically creates a number of plot events for each map
- Even basic plotting supports plot events through additional arguments to `plotOutput`
- To illustrate plot events, we will use `leaflet` events
### Leaflet's plot events
- Leaflet events are accessed like so:
::: {style="font-size: 20px;"}
`input$<Map ID>`{style="color: red;"}`_<Object type>`{style="color: green;"}`_<Event type>`{style="color: blue;"}
:::
- Map ID refers to the input ID given to the leaflet map
#### Leaflet object types
- "Object type" refers to the geometry, which can be one of:
- `marker` for points
- `shape` for polygons and lines
- `geojson` and `topojson` for data that was passed in GeoJSON or TopoJSON format
#### Leaflet event types
- "Event type" refers to the action that is performed on the geometry to trigger the event, one of:
- `click`
- `mouseover`
- `mouseout`
#### Other events
- Additionally, Leaflet has some more general events:
- `input$<Map ID>_click` triggers when the background of the map is clicked
- `input$<Map ID>_bounds` provides the bounding box of the current view
- `input$<Map ID>_zoom` provides the current zoom level
- `input$<Map ID>_center` provides the center point of the current view
## Appendix: Proxies
- Similar to plot events, most Shiny plotting frameworks implement what is called proxies
- A proxy is a representation of an existing widget
- Such proxies can be manipulated *in place*, i.e. they do not need to be re-rendered
### Proxies in Shiny frameworks
- Many Shiny extensions provide proxy functions:
- [`DT::dataTableProxy()`](https://rdrr.io/cran/DT/man/proxy.html)
- [`plotly::plotlyProxy()`](https://rdrr.io/cran/plotly/man/plotlyProxy.html)
- [`leaflet::leafletProxy()`](https://rstudio.github.io/leaflet/reference/leafletProxy.html)
### Proxy workflow
1. Initialize an isolated output widget (i.e., no dependencies) / `isolate()`
2. Create an observer that updates input dependencies / `observe()`
3. Invalidate an input
4. Remove existing features and add new ones

### Manipulating proxies
- Proxies are best combined with functions that add to, remove to, or clear a widget
- The following table summarizes these functions
+----------+----------------------------------------------------------------------+--------------------+-------------------+
| Category | Add functions | Remove | Clear |
+==========+======================================================================+====================+===================+
| tile | `addTiles()`, `addProviderTiles()` | `removeTiles()` | `clearTiles()` |
+----------+----------------------------------------------------------------------+--------------------+-------------------+
| marker | `addMarkers()`, `addCircleMarkers()` | `removeMarker()` | `clearMarkers()` |
+----------+----------------------------------------------------------------------+--------------------+-------------------+
| shape | `addPolygons()`, `addPolylines()`, `addCircles()`, `addRectangles()` | `removeShape()` | `clearShapes()` |
+----------+----------------------------------------------------------------------+--------------------+-------------------+
| geojson | `addGeoJSON()` | `removeGeoJSON()` | `clearGeoJSON()` |
+----------+----------------------------------------------------------------------+--------------------+-------------------+
| topojson | `addTopoJSON()` | `removeTopoJSON()` | `clearTopoJSON()` |
+----------+----------------------------------------------------------------------+--------------------+-------------------+
| control | `addControl()` | `removeControl()` | `clearControls()` |
+----------+----------------------------------------------------------------------+--------------------+-------------------+
### Synthesis: Plot events, proxies, and plot manipulation
- Proxies unleash their potential when combined with plot events and plot manipulation:
- This combination allows users to manipulate plots themselves (e.g. adding or removing elements)
- The following example makes use of all three concepts to create a map that can add and remove simple markers
- Plot events: `input$map_click` and `input$map_marker_click` to register where markers should be added and removed
- `leafletProxy("map")`: A proxy is needed to manipulate the map without resetting the view
- `addMarkers` and `removeMarker` to add and remove markers
```{r, eval=FALSE}
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output, session) {
# initial map render
output$map <- renderLeaflet({ # <1>
leaflet() %>% # <1>
addTiles() %>% # <1>
setView(lng = 7, lat = 52, zoom = 7) # <1>
}) # <1>
# add marker
observe({ # <2>
click <- input$map_click # <2>
leafletProxy("map") %>% # <2>
addMarkers(lng = click$lng, lat = click$lat, layerId = toString(click)) # <2>
}) %>% # <2>
bindEvent(input$map_click) # <2>
# remove marker
observe({ # <3>
click <- input$map_marker_click # <3>
leafletProxy("map") %>% # <3>
removeMarker(click$id) # <3>
}) %>% # <3>
bindEvent(input$map_marker_click) # <3>
}
shinyApp(ui, server)
```
1. Render the leaflet map once. Note that the render function does not take any dependencies and is thus only run once.
2. Add a marker every time the map is clicked somewhere. Note that the marker is added not to a new map, but to a proxy of the map that is already rendered.
3. Remove a marker that is clicked. Note how the observer is only triggered when a marker is clicked, i.e. when `input$map_marker_click` is triggered.
## Exercise session
### Plotly
::: callout-note
#### Exercise 1.1
Taking the ESS app (full code below), add an output canvas to the UI and a render function to the server function such that the new tab is able to display an interactive plotly widget.
```{r, eval=FALSE, file="shinyapps/example/app.R"}
#| code-fold: true
#| code-summary: "Complete code for the ESS app"
```
:::
::: {.callout-warning collapse="true"}
#### Solution 1.2
In the UI, add a new `tabPanel()` to the `tabsetPanel()`.
```{r, eval=FALSE}
#| source-line-numbers: "26-30"
mainPanel(
tabsetPanel(
type = "tabs",
### Table tab ----
tabPanel(
title = "Table",
div(
style = "height: 600px; overflow-y: auto;",
tableOutput("table")
)
),
### Plot tab ----
tabPanel(
title = "Plot",
plotlyOutput("plot", height = 600)
),
### Map tab ----
tabPanel(
title = "Map",
leafletOutput("map", height = 600)
),
### New tab ----
tabPanel(
title = "Histogram",
plotlyOutput("hist", height = 600)
)
)
)
```
In the server function, add `renderPlotly` and assign it to the output object.
```{r, eval=FALSE}
output$hist <- renderPlotly({
})
```
```{r, eval=FALSE}
#| code-fold: true
#| code-summary: "Complete code (important lines are highlighted)"
#| source-line-numbers: "92-96,209-211"
library(dplyr)
library(tidyr)
library(shiny)
library(plotly)
library(leaflet)
library(haven)
ess <- readRDS("ess_trust.rds")
ess_geo <- readRDS("ess_trust_geo.rds")
# UI ----
ui <- fluidPage(
titlePanel("European Social Survey - round 10"),
## Sidebar ----
sidebarLayout(
sidebarPanel(
### select dependent variable
selectInput(
"xvar",
label = "Select a dependent variable",
choices = c(
"Trust in country's parliament" = "trust_parliament",
"Trust in the legal system" = "trust_legal",
"Trust in the police" = "trust_police",
"Trust in politicians" = "trust_politicians",
"Trust in political parties" = "trust_parties",
"Trust in the European Parliament" = "trust_eu",
"Trust in the United Nations" = "trust_un"
)
),
### select a variable ----
selectInput(
"yvar",
label = "Select an independent variable",
choices = c(
"Placement on the left-right scale" = "left_right",
"Age" = "age",
"Feeling about household's income" = "income_feeling",
"How often do you use the internet?" = "internet_use",
"How happy are you?" = "happiness"
)
),
### select a country ----
selectizeInput(
"countries",
label = "Filter by country",
choices = unique(ess$country),
selected = "FR",
multiple = TRUE
),
### filter values ----
sliderInput(
"range",
label = "Set a value range",
min = min(ess$trust_parliament, na.rm = TRUE),
max = max(ess$trust_parliament, na.rm = TRUE),
value = range(ess$trust_parliament, na.rm = TRUE),
step = 1
)
),
## Main panel ----
mainPanel(
tabsetPanel(
type = "tabs",
### Table tab ----
tabPanel(
title = "Table",
div(
style = "height: 600px; overflow-y: auto;",
tableOutput("table")
)
),
### Plot tab ----
tabPanel(
title = "Plot",
plotlyOutput("plot", height = 600)
),
### Map tab ----
tabPanel(
title = "Map",
leafletOutput("map", height = 600)
),
### New tab ----
tabPanel(
title = "Histogram",
plotlyOutput("hist", height = 600)
)
)
)
)
)
# Server ----
server <- function(input, output, session) {
# update slider ----
observe({
var <- na.omit(ess[[input$xvar]])
is_ordered <- is.ordered(var)
var <- as.numeric(var)
updateSliderInput(
inputId = "range",
min = min(var),
max = max(var),
value = range(var),
step = if (is_ordered) 1
)
}) %>%
bindEvent(input$xvar)
# filter data ----
filtered <- reactive({
req(input$countries, cancelOutput = TRUE)
xvar <- input$xvar
yvar <- input$yvar
range <- input$range
# select country
ess <- ess[ess$country %in% input$countries, ]
# select variable
ess <- ess[c("idno", "country", xvar, yvar)]
# apply range
ess <- ess[ess[[xvar]] > range[1] & ess[[xvar]] < range[2], ]
ess
})
# render table ----
output$table <- renderTable({
filtered()
}, height = 400)
# render plot ----
output$plot <- renderPlotly({
xvar <- input$xvar
yvar <- input$yvar
plot_data <- filtered() %>%
drop_na() %>%
mutate(across(where(is.numeric), .fns = as.ordered))
p <- ggplot(plot_data) +
aes(x = .data[[xvar]], y = .data[[yvar]], group = .data[[xvar]]) +
geom_violin(fill = "lightblue", show.legend = FALSE) +
theme_classic()
ggplotly(p)
})
# render map ----
output$map <- renderLeaflet({
var <- input$xvar
ess_geo <- ess_geo[c("country", var)]
# create labels with a bold title and a body
labels <- sprintf(
"<strong>%s</strong><br>%s",
ess_geo$country,
ess_geo[[var]]
)
labels <- lapply(labels, HTML)
# create a palette for numerics and ordinals
if (is.ordered(ess_geo[[var]])) {
pal <- colorFactor("YlOrRd", domain = NULL)
} else {
pal <- colorNumeric("YlOrRd", domain = NULL)