-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshiny.qmd
1153 lines (918 loc) · 35.3 KB
/
shiny.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
# Shiny {#sec-shiny}
```{r}
#| eval: true
#| echo: false
#| include: false
source("_common.R")
```
```{r}
#| label: co_box_tldr
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "b",
look = "default", hsize = "1.10", size = "1.05",
header = "![](images/00_index_shiny.png){height=40} TLDR",
fold = TRUE,
contents = "
<br>
A basic **Shiny project** has two files:
An `app.R` and `.Rproj` file:\n
\`\`\`bash
shiny-app/
├── app.R
└── shiny-app.Rproj
\`\`\`
A fully developed **Shiny project** can have the following:
1. An `R/` folder for additional scripts (i.e., modules, helper & utility functions) that is automatically sourced when the application runs\n
    - The only exception to this is a `global.R` file, which is run first\n
2. A `www/` folder for external resources (images, styling, etc.) that is automatically served when the application runs\n
3. An optional `DESCRIPTION` file that controls deployment behaviors (i.e., `DisplayMode`)\n
4. Data files\n
5. An optional `README.md` file for documentation\n
\`\`\`bash
shiny-app/
├── DESCRIPTION
├── R/
│ ├── module.R
│ ├── helper.R
│ └── utils.R
├── README.md
├── app.R
├── data.RData
├── shiny-app.Rproj
└── www/
└── shiny.png
\`\`\`
\\*[Both `R/` and `www/` are automatically loaded when the app launches.]{style='font-style: italic;'}
"
)
```
---
::: {layout="[90, 10]" layout-valign="top"}
This chapter briefly reviews programming with Shiny's reactive model and how it differs from regular R programming. Then, I'll cover some of the unique behaviors of Shiny app projects (and why you might consider adopting them if you haven't already).
![](images/00_index_shiny.png){fig-align="right"}
:::
```{r}
#| label: shinypak_apps
#| echo: false
#| results: asis
#| eval: true
shinypak_apps(regex = "^02", branch = "02.1_shiny-app")
```
## Shiny basics {.unnumbered}
Reactivity is the process that lets Shiny apps respond to user actions automatically. When developing Shiny apps, we need to connect inputs, reactivity, and outputs to manage how the app behaves and predict its actions.
Shiny programming is different from regular R programming in a few important ways:
- **An Event-driven UI**: Shiny apps require developers to create a user interface (UI) that helps users navigate the app. The UI registers user actions, such as button clicks or input changes, which trigger updates in the application.[^shiny-event-ui]
- Regular R programming often involves executing predefined steps or functions without direct interaction or responses to user events.
- **A Reactive Server**: In Shiny, the app reacts based on how inputs, values, and outputs are connected, which means that when a user makes a change, those changes are automatically shared throughout the app.
- In standard R programming, we write functions to process data and generate outputs like graphs, tables, and model results. This method does not account for reactivity or downstream changes.
Learning reactivity can be challenging when you start, but fortunately, there are [excellent tutorials](https://shiny.posit.co/r/getstarted/shiny-basics/lesson1/index.html) and [articles](https://shiny.posit.co/r/articles/build/understanding-reactivity/) to help you along the way!
[^shiny-event-ui]: Shiny apps require developers to design and develop a user interface (UI). [User experience (UX) design](https://bootcamp.cvn.columbia.edu/blog/what-is-ux-design/#:~:text) is an entirely separate field, but as Shiny developers, we need to know enough to allow users to interact with and navigate our apps.
## Shiny projects ![](images/rproj_icon.png){height=30} {#sec-shiny-projects}
```{r}
#| label: git_box_moviesApp_main
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = 'launch',
fig_pw = '75%',
branch = "02.1_shiny-app",
repo = 'sap')
```
RStudio's **New Project Wizard** ![](images/rstudio-icon.png){height=20} can be used to create a new Shiny application project:
![New Shiny app project](images/shiny_new_project_wizard.png){width="75%" fig-align="center"}
New app projects need a name and location:
![We can also decide whether we want to use Git or `renv`](images/shiny_new_shiny_proj.png){width="75%" fig-align="center"}
### Boilerplate [`app.R`]{style='font-size: 1.05em;'} {#sec-boilerplate-app-dot-r}
Note that the only items in the new Shiny app project are `app.R` and the `sap.Rproj` file.
```{bash}
#| eval: false
#| code-fold: false
sap/
├── app.R
└── sap.Rproj
1 directory, 2 files
```
If you've created a new app project in RStudio ![](images/rstudio-icon.png){height=20}, the `app.R` initially contains a boilerplate application, which we can launch by clicking on the **Run App** button:
::: {.column-margin}
![Click on **Run App**](images/shiny_run_app.png){width="75%" fig-align="center"}
:::
::: {#fig-shiny_old_faithful}
![Old Faithful geyser app](images/shiny_old_faithful.png){#fig-shiny_old_faithful width="100%" fig-align="center"}
Boilerplate Old Faithful geyser app in new Shiny projects
:::
The boilerplate 'Old Faith Geyser Data' app is a perfect example of what Shiny can do with a single `app.R` file, but we'll want to exchange this code for a more realistic application.
## Movies app {#sec-introduce-movie-review-app}
```{r}
#| label: git_launch_02.2_movies-app
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
branch = "02.2_movies-app")
```
The next few sections will cover some intermediate/advanced Shiny app features using the Shiny app from the '[Building Web Applications with Shiny](https://rstudio-education.github.io/shiny-course/)' course. This app is a great example for the following reasons:
1. It has **multiple input types** that are collected in the UI
2. The graph output can be converted to a **utility function**
3. The app loads an **external data** file when it's launched
4. The code is accessible (and comes from a trusted source)
As Shiny applications become more complex, they often grow beyond just one `app.R` file. Knowing how to store utility functions, data, documentation, and metadata is important to manage this complexity. This preparation helps us successfully organize our Shiny apps into R packages.
### app.R {#sec-initial-movie-review-app-dot-r}
The code below replaces our boilerplate 'Old Faith Geyser Data' app in `app.R`:
```{r}
#| code-fold: true
#| eval: false
#| code-summary: 'show/hide movie review Shiny app'
ui <- shiny::fluidPage(
theme = shinythemes::shinytheme("spacelab"),
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::selectInput(
inputId = "y",
label = "Y-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "audience_score"
),
shiny::selectInput(
inputId = "x",
label = "X-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "critics_score"
),
shiny::selectInput(
inputId = "z",
label = "Color by:",
choices = c(
"Title Type" = "title_type",
"Genre" = "genre",
"MPAA Rating" = "mpaa_rating",
"Critics Rating" = "critics_rating",
"Audience Rating" = "audience_rating"
),
selected = "mpaa_rating"
),
shiny::sliderInput(
inputId = "alpha",
label = "Alpha:",
min = 0, max = 1,
value = 0.4
),
shiny::sliderInput(
inputId = "size",
label = "Size:",
min = 0, max = 5,
value = 3
),
shiny::textInput(
inputId = "plot_title",
label = "Plot title",
placeholder = "Enter text to be used as plot title"
),
shiny::actionButton(
inputId = "update_plot_title",
label = "Update plot title"
)
),
shiny::mainPanel(
shiny::br(),
shiny::p(
"These data were obtained from",
shiny::a("IMBD", href = "http://www.imbd.com/"), "and",
shiny::a("Rotten Tomatoes", href = "https://www.rottentomatoes.com/"), "."
),
shiny::p(
"The data represent",
nrow(movies),
"randomly sampled movies released between 1972 to 2014 in the United States."
),
shiny::plotOutput(outputId = "scatterplot"),
shiny::hr(),
shiny::p(shiny::em(
"The code for this Shiny application comes from",
shiny::a("Building Web Applications with shiny",
href = "https://rstudio-education.github.io/shiny-course/"
)
))
)
)
)
server <- function(input, output, session) {
new_plot_title <- shiny::reactive({
tools::toTitleCase(input$plot_title)
}) |>
shiny::bindEvent(input$update_plot_title,
ignoreNULL = FALSE,
ignoreInit = FALSE
)
output$scatterplot <- shiny::renderPlot({
scatter_plot(
df = movies,
x_var = input$x,
y_var = input$y,
col_var = input$z,
alpha_var = input$alpha,
size_var = input$size
) +
ggplot2::labs(title = new_plot_title()) +
ggplot2::theme_minimal() +
ggplot2::theme(legend.position = "bottom")
})
}
shiny::shinyApp(ui = ui, server = server)
```
### Utility functions {#sec-initial-movie-review-utils}
I've converted `ggplot2` server code into a `scatter_plot()` utility function:
```{r}
#| code-fold: true
#| eval: false
#| code-summary: 'show/hide scatter_plot()'
scatter_plot <- function(df, x_var, y_var, col_var, alpha_var, size_var) {
ggplot2::ggplot(data = df,
ggplot2::aes(x = .data[[x_var]],
y = .data[[y_var]],
color = .data[[col_var]])) +
ggplot2::geom_point(alpha = alpha_var, size = size_var)
}
```
This function is stored in a new `utils.R` file:
### Data {#sec-initial-movie-review-data}
The `movies.RData` dataset contains reviews from [IMDB](https://www.imdb.com/) and [Rotten Tomatoes](https://www.rottentomatoes.com/). You can download these data [here](https://github.com/mjfrigaard/bbsa/raw/main/movies.RData). The `sap` project now contains the following files:
```{bash}
#| eval: false
#| code-fold: false
sap/
├── app.R
├── movies.RData
├── sap.Rproj
└── utils.R
2 directories, 4 files
```
To run the `movies` app, we need to load the data and source the `utils.R` file by adding the code below to the top of the `app.R` file:
```{r}
#| eval: false
#| code-fold: false
# install ------------------------------------
# install pkgs, then comment or remove below
pkgs <- c("shiny", "shinythemes", "stringr", "ggplot2", "rlang") # <1>
install.packages(pkgs, verbose = FALSE) # <1>
# <1>
# packages ------------------------------------
library(shiny)
library(shinythemes)
library(stringr)
library(ggplot2)
library(rlang)
# data -----------------------------------------
load("movies.RData")
# utils ----------------------------------------
source("utils.R")
```
1. Install `pkgs`, then comment or remove below
Clicking on **Run App** displays the movie review app:
![Movie review app](images/shiny_movies_app.png){width="100%" fig-align="center"}
## Folders {#sec-shiny-folders}
Now that we have a *slightly* more complex application in `app.R`, I’ll add a few project folders we can include in our project that have unique built-in behaviors. These folders will help organize your files and make additional resources available to your app.
```{r}
#| label: git_launch_03_proj-app
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
branch = "02.3_proj-app")
```
### R/
If your Shiny app relies on utility or helper functions outside the `app.R` file, place this code in an `R/` folder. Any `.R` files in the `R/` folder will be automatically sourced when the application is run.
::: {.callout-note title="Place `utils.R` in `R/` folder" collapse='false' appearance='simple'}
I've moved the `utils.R` file into the `R/` folder in `sap`:
```{bash}
#| eval: false
#| code-fold: false
sap/
└── R/
└── utils.R
1 directory, 1 file
```
:::
Shiny's [`loadSupport()`](https://shiny.posit.co/r/reference/shiny/1.5.0/loadsupport) function makes this process possible. We'll return to this function in a later chapter, because the `R/` folder has a similar behavior in R packages.[^load-support-1]
[^load-support-1]: Shiny introduced these features in version 1.3.2.9001, and you can read more about them in the section titled, '*The `R/` directory*' in [App formats and launching apps](https://shiny.posit.co/r/articles/build/app-formats/)
### www/
When you run a Shiny application, any static files (i.e., resources) under a `www/` directory will automatically be made available within the application. This folder stores images, CSS or JavaScript files, and other static resources.
::: {.callout-note title="Create `www/` folder and download image" collapse='false' appearance='simple'}
I've downloaded the Shiny logo ([`shiny.png`](https://raw.githubusercontent.com/rstudio/hex-stickers/main/PNG/shiny.png)) and stored it in the `www/` folder.
```{bash}
#| eval: false
#| code-fold: false
sap/
└── www/
└── shiny.png
1 directory, 1 file
```
In the section below, we'll reference `shiny.png` directly in the UI.
:::
Following the conventional folder structure will also help set you up for success when/if you decide to convert it into an app-package.
## Files {#sec-shiny-files}
The sections below cover additional files to include in your Shiny app. None of these files are required, but including them will make the transition to package development smoother.
### README
Including a `README.md` file in your root folder is a good practice for any project. Using the standard markdown format (`.md`) guarantees it can be read from GitHub, too. `README.md` files should contain relevant documentation for running the application.
::: {.callout-note title="Create `README.md`" collapse='false' appearance='simple'}
I've included the content below in the `README.md` file
```Markdown
# movies app
The original code and data for this Shiny app comes from the [Building Web Applications with Shiny](https://rstudio-education.github.io/shiny-course/) course. It's been converted to use [shiny modules](https://shiny.posit.co/r/articles/improve/modules/).
View the code for this application in the [`sap` branches](https://github.com/mjfrigaard/sap/branches/all).
```
:::
### DESCRIPTION
`DESCRIPTION` files play an essential role in R packages, but they are also helpful in Shiny projects if I want to deploy the app in [showcase mode](https://shiny.posit.co/r/articles/build/display-modes/).
::: {.callout-note title="Create `DESCRIPTION`" collapse='false' appearance='simple'}
I've included the content below in `DESCRIPTION`:
```{bash}
#| eval: false
#| code-fold: false
Type: shiny
Title: movies app
Author: John Smith
DisplayMode: Showcase
```
:::
::::{.column-margin}
:::{style="font-weight: bold; font-size: 1.10em"}
*It's always a good idea to leave at least one `<empty final line>` in your `DESCRIPTION` file.*
:::
::::
After adding `README.md` and a `DESCRIPTION` file (listing `DisplayMode: Showcase`), the movies app will display the code and documentation when the app launches.[^showcase-mode]
[^showcase-mode]: Read more about `showcase` mode [here](https://shiny.posit.co/r/articles/build/display-modes/)
## Code {#sec-app-code}
The following two items are considered best practices because they make your app more scalable by converting `app.R` into functions.
### Modules {#sec-shiny-modules}
Shiny modules are a '[pair of UI and server functions](https://mastering-shiny.org/scaling-modules.html)' designed to compartmentalize input and output IDs into distinct namespaces,
> *'...a namespace is to an ID as a directory is to a file...'* - [`shiny::NS()` help file](https://shiny.posit.co/r/reference/shiny/latest/ns)
Module UI functions usually combine the layout, input, and output functions using `tagList()`. Module server functions handle the 'backend' code within a Shiny server function. The UI and server module functions connect through an `id` argument. The UI function creates this `id` with `NS()` (namespace), and the server function uses `moduleServer()` to call it.
#### Inputs
The `mod_var_input_ui()` function creates a list of inputs (column names and graph aesthetics) in the UI:
```{r}
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide mod_var_input_ui()'
mod_var_input_ui <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
shiny::selectInput(
inputId = ns("y"), # <1>
label = "Y-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "audience_score"
),
shiny::selectInput(
inputId = ns("x"), # <2>
label = "X-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "imdb_rating"
),
shiny::selectInput(
inputId = ns("z"), # <3>
label = "Color by:",
choices = c(
"Title Type" = "title_type",
"Genre" = "genre",
"MPAA Rating" = "mpaa_rating",
"Critics Rating" = "critics_rating",
"Audience Rating" = "audience_rating"
),
selected = "mpaa_rating"
),
shiny::sliderInput(
inputId = ns("alpha"), # <4>
label = "Alpha:",
min = 0, max = 1, step = 0.1,
value = 0.5
),
shiny::sliderInput(
inputId = ns("size"), # <5>
label = "Size:",
min = 0, max = 5,
value = 2
),
shiny::textInput(
inputId = ns("plot_title"), # <6>
label = "Plot title",
placeholder = "Enter plot title"
)
)
}
```
1. `y` axis numeric variable
2. `x` axis numeric variable
3. `z` axis categorical variable
4. `alpha` numeric value for points
5. `size` numeric value for size
6. `plot_title` text
`mod_var_input_server()` returns these values in a reactive list:
```{r}
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide mod_var_input_server()'
mod_var_input_server <- function(id) {
shiny::moduleServer(id, function(input, output, session) {
return(
reactive({
list(
"y" = input$y, # <1>
"x" = input$x, # <2>
"z" = input$z, # <3>
"alpha" = input$alpha, # <4>
"size" = input$size, # <5>
"plot_title" = input$plot_title # <6>
)
})
)
})
}
```
1. `y` axis numeric variable
2. `x` axis numeric variable
3. `z` axis categorical variable
4. `alpha` numeric value for points
5. `size` numeric value for size
6. `plot_title` text
```{=html}
<style>
.codeStyle span:not(.nodeLabel) {
font-family: monospace;
font-size: 1.5em;
font-weight: bold;
color: #9753b8 !important;
background-color: #f6f6f6;
padding: 0.2em;
}
</style>
```
```{mermaid}
%%| fig-align: center
%%| fig-cap: 'Variable input module'
%%{init: {'theme': 'neutral', 'themeVariables': { 'fontFamily': 'monospace',"fontSize":"13px"}}}%%
flowchart LR
UI["<code>mod_var_input_ui()</code> Collects inputs"] -->|"<strong>UI Inputs</strong>"| Server["<code>mod_var_input_server()</code> Returns reactives"]
subgraph Inputs["<code>inputs$</code>"]
Axes("X, Y & Color")
Aes("Transparency")
Size("Point Size")
Title("Plot Title")
end
UI --> Axes
UI --> Aes
UI --> Size
UI -.-> Title
Axes -->|String| Server
Aes -->|Numeric| Server
Size -->|Numeric| Server
Title -.->|String| Server
```
#### Display
`mod_scatter_display_ui()` creates a dedicated namespace for the plot output (along with some help text):
```{r}
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide mod_scatter_display_ui()'
mod_scatter_display_ui <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
shiny::tags$br(),
shiny::tags$blockquote(
shiny::tags$em(
shiny::tags$h6("The data for this application comes from the ",
shiny::tags$a("Building web applications with Shiny",
href = "https://rstudio-education.github.io/shiny-course/"),
"tutorial"))
),
shiny::plotOutput(outputId = ns("scatterplot")) # <1>
)
}
```
1. Namespaced module `id` for plot in UI
`mod_scatter_display_server()` loads the `movies` data and collects the returned reactive list (`var_inputs()`) from `mod_var_input_server()` as `inputs()`. The `inputs()` reactive is passed to the utility function (`scatter_plot()`), then creates the `plot` object and adds the `plot_title()` and theme:
```{r}
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide mod_scatter_display_server()'
mod_scatter_display_server <- function(id, var_inputs) {
shiny::moduleServer(id, function(input, output, session) {
load("movies.RData") # <1>
inputs <- shiny::reactive({ # <2>
plot_title <- tools::toTitleCase(var_inputs()$plot_title) # <2>
list( # <2>
x = var_inputs()$x, # <2>
y = var_inputs()$y, # <2>
z = var_inputs()$z, # <2>
alpha = var_inputs()$alpha, # <2>
size = var_inputs()$size, # <2>
plot_title = plot_title # <2>
) # <2>
}) # <2>
output$scatterplot <- shiny::renderPlot({ # <3>
plot <- scatter_plot( # <3>
df = movies, # <3>
x_var = inputs()$x, # <3>
y_var = inputs()$y, # <3>
col_var = inputs()$z, # <3>
alpha_var = inputs()$alpha, # <3>
size_var = inputs()$size # <3>
) # <3>
plot + # <4>
ggplot2::labs( # <4>
title = inputs()$plot_title, # <4>
x = stringr::str_replace_all( # <4>
tools::toTitleCase( # <4>
inputs()$x), # <4>
"_", " "), # <4>
y = stringr::str_replace_all( # <4>
tools::toTitleCase( # <4>
inputs()$y), # <4>
"_", " ") # <4>
) +
ggplot2::theme_minimal() + # <5>
ggplot2::theme(legend.position = "bottom") # <5>
})
})
}
```
1. loading the `movies` data
2. assembling the returned values from `mod_var_input_server()`, and creating the `input()` reactive
3. `scatter_plot()` utility function creates the `plot` object
4. adds the `plot_title()`
5. add `theme` to layers
```{=html}
<style>
.codeStyle span:not(.nodeLabel) {
font-family: monospace;
font-size: 1.5em;
font-weight: bold;
color: #9753b8 !important;
background-color: #f6f6f6;
padding: 0.2em;
}
</style>
```
```{mermaid}
%%| fig-align: center
%%| fig-cap: 'Display module'
%%{init: {'theme': 'neutral', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"13px"}}}%%
flowchart TD
UI["<code>mod_scatter_display_ui</code><br>Plot display interface"]
Server["<code>mod_scatter_display_server()</code><br>Creates graph <code>inputs()</code>"]
Server -->|Calls utility<br>function| PlotUtility[["<code>scatter_plot()</code><br>Generates plot"]]
subgraph VarInputs["<code>mod_var_input_server()</code>"]
Axis("X, Y and Color")
Alpha("Transparency")
Size("Point Size")
Title["Plot Title"]
end
VarInputs -->|"Returns reactive"| Inputs
Inputs("<code>var_inputs()</code>") -->|"Input argument"|Server
PlotUtility -->|"Outputs"|UI
UI -->|"Displays"|Display(["Rendered scatter plot"])
style UI stroke-width:2px,rx:10,ry:10
style Server stroke-width:2px,rx:10,ry:10
style PlotUtility stroke-width:2px,rx:10,ry:10
```
Both UI and server module functions are combined into a single `.R` file, and all modules are placed in the `R/` folder so they are sourced when the application is run.
```{bash}
#| eval: false
#| code-fold: false
R/
├── mod_scatter_display.R
├── mod_var_input.R
└── utils.R
```
### Standalone app function {#sec-shiny-standalone-app-fun}
Instead of using `shiny::shinyApp()` (or the **Run App** icon), we'll want a custom standalone app function to launch our application. This give us more flexibility and control with our modules (and makes debugging easier).
```{r}
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide launch_app()'
launch_app <- function() {
shiny::shinyApp(
ui = shiny::fluidPage(
shiny::titlePanel(
shiny::div(
shiny::img(
src = "shiny.png",
height = 60,
width = 55,
style = "margin:10px 10px"
),
"Movies Reviews"
)
),
shiny::sidebarLayout(
shiny::sidebarPanel(
mod_var_input_ui("vars") # <1>
),
shiny::mainPanel(
mod_scatter_display_ui("plot") # <2>
)
)
),
server = function(input, output, session) {
selected_vars <- mod_var_input_server("vars") # <3>
mod_scatter_display_server("plot", var_inputs = selected_vars) # <4>
}
)
}
```
1. Variable input UI module
2. Graph display UI module
3. Variable input server module
4. Graph display server module
The `id` arguments (`"vars"` and `"plot"`) connect the UI functions to their server counterparts, and the output from `mod_var_input_server()` is the `var_inputs` argument in `mod_scatter_display_server()`.
```{=html}
<style>
.codeStyle span:not(.nodeLabel) {
font-family: monospace;
font-size: 1.5em;
font-weight: bold;
color: #9753b8 !important;
background-color: #f6f6f6;
padding: 0.2em;
}
</style>
```
```{mermaid}
%%| fig-align: center
%%| fig-cap: 'Standalone app function'
%%{init: {'theme': 'neutral', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"13px"}}}%%
flowchart LR
subgraph Launch["<code>launch_app()</code>"]
subgraph VarNS["Variable (<code>vars</code>) Namespace"]
VarInpuUI["UI Module:<br><code>mod_var_input_ui()</code>"]
VarInpuServer["Server Module:<br><code>mod_var_input_server()</code>"]
VarInpuUI <--> VarInpuServer
end
subgraph GraphNS["Graph (<code>plot</code>) Namespace"]
DisplayUI["UI Module:<br><code>mod_scatter_display_ui()</code>"]
DisplayServer["Server Module:<br><code>mod_scatter_display_server()</code>"]
PlotUtil["Utility Function:<br><code>scatter_plot()</code>"]
VarInpuServer <-->|"selected_vars"|DisplayServer
DisplayServer <-.-> PlotUtil <--> DisplayUI
end
end
VarNS <==>|"Communicates<br>across namespaces"| GraphNS
```
To launch our app, we place the call to `shinyApp()` in a `launch_app()` function in `app.R`. Both module functions are combined in the `ui` and `server` arguments of `shinyApp()`.
```{r}
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide launch_app() in app.R'
# install ------------------------------------
# after installing, comment this out
pkgs <- c("shiny", "shinythemes", "stringr", "ggplot2", "rlang") # <1>
install.packages(pkgs, verbose = FALSE) # <1>
# packages ------------------------------------
library(shiny) # <2>
library(shinythemes) # <2>
library(stringr) # <2>
library(ggplot2) # <2>
library(rlang) # <2>
launch_app <- function() {
shiny::shinyApp(
ui = shiny::fluidPage(
shiny::titlePanel(
shiny::div(
shiny::img(
src = "shiny.png",
height = 60,
width = 55,
style = "margin:10px 10px"
),
"Movies Reviews"
)
),
shiny::sidebarLayout(
shiny::sidebarPanel(
mod_var_input_ui("vars") # <3>
),
shiny::mainPanel(
mod_scatter_display_ui("plot") # <4>
)
)
),
server = function(input, output, session) {
selected_vars <- mod_var_input_server("vars") # <5>
mod_scatter_display_server("plot", var_inputs = selected_vars) # <6>
}
)
}
launch_app()
```
1. Header (comment this out after the packages are installed)
2. Load packages
3. Variable input UI module
4. Graph display UI module
5. Variable input server module
6. Graph display server module
Now, I can run the app with `launch_app()`.
![View a deployed version [here](https://mjfrigaard.shinyapps.io/moviesApp/)](images/shiny_proj_movies_app.png){width="100%" fig-align="center"}
The deployed files of `sap` are below:
```{bash}
#| eval: false
#| code-fold: false
sap/ # 02.3_proj-app branch
├── DESCRIPTION
├── R/
│ ├── mod_scatter_display.R
│ ├── mod_var_input.R
│ └── utils.R
├── README.md
├── app.R
├── movies.RData
├── sap.Rproj
├── rsconnect/
│ └── shinyapps.io/
│ └── user/
│ └── sap.dcf
└── www/
└── shiny.png
6 directories, 10 files
```
:::{.column-margin}
The `rsconnect/` folder has been removed from the [`02.3_proj-app`](https://github.com/mjfrigaard/sap/tree/02.3_proj-app) branch.
:::
## Additional features {#sec-adv-shiny-projects}
Below are two additional 'optional' features that *can* be included with your Shiny application. I consider these 'optional' because they're use depends on the specific needs and environment for each application.
### Globals
Placing a `global.R` file in your root folder (or in the `R/` directory) causes this file to be sourced only once when the Shiny app launches, rather than each time a new user connects to the app. `global.R` is commonly used for initializing variables, loading libraries, loading large data sets and/or performing initial calculations.
::: {.callout-note title="Using `global.R`" collapse='true' appearance='simple'}
I *could* place the header from `app.R` in `global.R` to ensure these packages are loaded before the application launches:
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide contents of R/global.R'
# packages ------------------------------------
library(shiny)
library(shinythemes)
library(stringr)
library(ggplot2)
library(rlang)
```
`global.R` can be placed in the `R/` folder
```{bash}
#| eval: false
#| code-fold: false
R/
├── global.R
├── mod_scatter_display.R
├── mod_var_input.R
└── utils.R
1 directory, 4 files
```
Or in the project root folder