-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhello-ui.qmd
884 lines (601 loc) · 29.1 KB
/
hello-ui.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
---
always_allow_html: true
---
# User interface (UI)
```{r setup, include=FALSE}
library(shiny)
library(tidyverse)
library(rsconnect)
knitr::opts_chunk$set(
echo = FALSE,
fig.align = "center",
out.width = "100%"
)
```
In this section we'll build the user interface of a simple app.
However, before we get into the weeds of building a user interface, let's revisit the anatomy of a Shiny app.
```{r}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
```
- The user interface, that we'll refer to as the "UI" going forward, defines and lays out the inputs of your app where users can make their selections. It also lays out the outputs.
- The server function, on the other hand, calculates outputs and performs any other calculations needed for the outputs.
### Example
```{r}
knitr::include_graphics("images/ui-to-scatterplot.png")
```
For example, if your app features a plot the code for building that plot lives in the server function. But the setup for the user defined inputs for the plot, as well as information on where physically on the app the plot should appear, are defined in the UI.
###
Here is the app we'll work with in this section and the code that builds the UI of that app.
Since this is too much code to parse, we'll explore individual components of the UI one by one.
```{r}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
knitr::include_graphics("images/ui-selectinput-scatterplot.png")
```
### `fluidPage()`
At the outermost layer of our UI definition we begin with the `fluidPage()` function.
```{r}
knitr::include_graphics("images/fluidPage.png")
```
The `fluidPage()` function creates a fluid page layout consisting of rows and columns. Rows make sure that elements in them appear on the same line. Columns within these rows define how much horizontal space each element should occupy.
Fluid pages scale their components in realtime to fill all available browser width, which means you, the app developer, don't need to worry about defining relative widths for individual app components.
As always, for more information on arguments to this function, you can view the R function help by typing `?fluidPage` in your R console or visiting the function reference page on the package website [here](https://shiny.rstudio.com/reference/shiny/latest/).
### Layout
Next, we define the layout of our app with `sidebarLayout()`.
```{r}
knitr::include_graphics("images/layout.png")
```
Shiny includes a number of options for laying out the components of an application. The default layout, the one we're using in our example app, is a layout with a sidebar, that you can define with the `sidebarLayout()` function.
```{r}
knitr::include_graphics("images/layout-app.png")
```
This is a simple layout with a narrow sidebar for inputs and a wider main area for output.
Under the hood, Shiny implements layout features available in Bootstrap 2, which is a popular HTML/CSS framework. However the nice thing about working in Shiny is that no prior experience with Bootstrap is necessary.
To learn more about various layouts, I recommend reviewing the [Application Layout Guide article](https://shiny.rstudio.com/articles/layout-guide.html) at [shiny.rstudio.com](shiny.rstudio.com).
### Input controls
Next we define our sidebar panel containing input controls.
```{r}
knitr::include_graphics("images/input-controls.png")
```
###
This panel contains two dropdown menus created with the `selectInput()` function.
```{r}
knitr::include_graphics("images/input-dropdowns.png")
```
###
Let's take a look at one of the `selectInput` widgets a little more closely.
```{r}
knitr::include_graphics("images/input-closeup.png")
```
1. The first argument is the `inputId`, which is the input value that the app will internally use to access the value selected by the user.
2. The second argument is the `label`, which is the display label that the user sees.
3. The third argument is the list of `choices` the user will choose from. In this app, these are variable names from the movies dataset.
4. And lastly we specify a default selection from that list with `selected`.
### Main Panel
The final component of our UI is `mainPanel()`.
```{r}
knitr::include_graphics("images/main-panel.png")
```
Currently the main panel contains only one component, a plot output. We'll talk about how this plot is built later in the tutorial.
Next, let's practice building an app UI!
### Practice: Extend the UI
We'll start with a simplified version of the app you saw in the previous exercise. In this app a `selectInput()` widget is used to allow the user to select which variables should be plotted on the `x` and `y` axes of the scatterplot.
The `selectInput()` function has the following arguments:
- an `inputId` that is used to refer to the input parameter when building the scatterplot,
- a list of `choices` to pick from (which must match variable names in the data frame),
- and a `selected` choice for when the app first launches.
#### Your turn
Modify the Shiny app code in `app.R` / shown below:
- In the `ui`:
- Add a new `selectInput` widget to color the points by a choice of the following variables: `"title_type"`, `"genre"`, `"mpaa_rating"`, `"critics_rating"`, `"audience_rating"`.
- Make the default selection `"mpaa_rating"`.
- Use `"z"` as the `inputId`.
- `label` can be whatever you like.
- In the `server`:
- Set the color argument in `ggplot()` aesthetic mappings to `input$z`.
::: proj
*Complete this exercise by opening up the RStudio Project titled **1-2a Extend the UI** within your RStudio Cloud Workspace*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Workspace](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-1-2a-selectInput, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "audience_score"),
# Select variable for x-axis
selectInput(inputId = "x",
label = "X-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "critics_score"),
# Select variable for color
selectInput(inputId = "___",
label = "____",
choices = c(___),
selected = "___")
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y,
color = ___)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
<details>
<summary>
Show solution
</summary>
See the following code chunk for the solution to the exercise above.
```{r ex-1-2a-selectInput-solution, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "audience_score"),
# Select variable for x-axis
selectInput(inputId = "x",
label = "X-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "critics_score"),
# Select variable for color
selectInput(inputId = "z",
label = "Color by:",
choices = c("title_type", "genre", "mpaa_rating", "critics_rating", "audience_rating"),
selected = "mpaa_rating")
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y,
color = input$z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice: Extend the UI further
The potential variables the user can select for the `x` and `y` axes and `color` currently appear in the UI of the app the same way that they are spelled in the data frame header. However we might want to label them in a way that is more human readable. We can achieve this using named vectors for the `choices` argument, in the format of `"Human readable label" = "variable_name"`.
#### Your turn
- Fill in the blanks in the code below with human readable labels for `x` and `y` inputs.
- Re-create the `selectInput` widget for color, `z`, with options `"title_type"`, `"genre"`, `"mpaa_rating"`, `"critics_rating"`, and `"audience_rating"`, default selection `"mpaa_rating"` just like in the previous exercise, but this time use human readable labels as well.
::: proj
*Complete this exercise by opening up the RStudio Project titled **1-2b Extend the UI further** within your RStudio Cloud Workspace*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Workspace](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-1-2b-selectInput-labels, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
selectInput(inputId = "y",
label = "Y-axis:",
choices = c(___ = "imdb_rating",
___ = "imdb_num_votes",
___ = "critics_score",
___ = "audience_score",
___ = "runtime"),
selected = "audience_score"),
# Select variable for x-axis
selectInput(inputId = "x",
label = "X-axis:",
choices = c(___ = "imdb_rating",
___ = "imdb_num_votes",
___ = "critics_score",
___ = "audience_score",
___ = "runtime"),
selected = "critics_score"),
# Select variable for color
selectInput(inputId = "z",
label = "Color:",
choices = ___,
selected = ___)
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y,
color = input$z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
<details>
<summary>
Show solution
</summary>
See the following code chunk for the solution to the exercise above.
```{r ex-1-2b-selectInput-labels-solution, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
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"),
# Select variable for x-axis
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"),
# Select variable for color
# Select variable for color
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")
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y,
color = input$z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
## Server function
Now that you've had some practice with the UI, it's time to move on to the server function.
Again, before we get into the details, let's remind ourselves of the anatomy of a Shiny app. The basic task of the server function is to define the relationship between inputs and outputs.
### Here again is the app that we are working with in this module
Earlier we saw how to build the UI of this app, and we also noted that each input was tagged with an `inputId` that can be used to refer to them in the server.
```{r}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
```
### This is the server function code for this app
Once again there is a lot going on here to parse at once, so in the following sections we take a closer look at the function.
```{r}
knitr::include_graphics("images/server.png")
```
### At the outermost layer
```{r}
knitr::include_graphics("images/server-outermost.png")
```
We define our server function which takes two arguments: an `input` and an `output`. Both of these are named lists.
The server function accesses inputs selected by the user to perform computations and specifies how outputs laid out in the UI should be updated.
The server function can take on one more argument, `session`, which is an environment that can be used to access information and functionality relating to the session. However this concept is beyond the scope of this tutorial, so for now we'll stick to server functions that only have input and output arguments.
### `output`
Our simple app had only one output -- a plot. So our server function contains the logic necessary to build this plot.
```{r}
knitr::include_graphics("images/output.png")
```
The `renderPlot()` function specifies how the plot output should be updated. Let's take a look at what is happening in the `renderPlot()` function first.
### `renderPlot()`
```{r}
knitr::include_graphics("images/renderplot.png")
```
This is good ol' ggplot2 code! So even if you're new to shiny, if you've previously used ggplot2 for plotting in R, this syntax should look familiar to you.
One aspect of the syntax that might be new, however, is how the x and y variables are defined. They come from the input list that is built in the UI.
### Inputs
Here is the relevant UI and server code.
```{r}
knitr::include_graphics("images/inputs-x-y.png")
```
Input x and y come from the `selectInput()` widgets, and map to the `x` and `y` arguments of the plot aesthetics.
### Rules of server functions
There are three rules of building server functions:
1. Always save objects to display to the named output list, i.e. something of the form `output$xx`, where `xx` is the plot you want to display.
2. Always build objects to display with one of the `render*()` functions, like we built our plot with `renderPlot()`.
3. Use input values from the named input list, with `input$xx`.
### Output types
Just like various inputs, Shiny also provides a wide selection of output types each of which works with a render function.
```{r, out.width = "80%"}
knitr::include_graphics("images/cheatsheet-outputs.png")
```
For example, in our app we used the `renderPlot()` function to build our reactive plot (we'll get to what I mean by reactive in a second) and laid out the plot with the `plotOutput()` function.
```{r}
knitr::include_graphics("images/render-output-pairs.png")
```
Shiny knows to match these two together as they use the same `outputID`, scatterplot.
In the following exercises you'll get a chance to work with other render/output function pairs to add more elements to your app.
### Practice: Matching inputs and outputs
Here is a simple Shiny app. Try entering some text and observe how the text is displayed back to you after a short pause.
------------------------------------------------------------------------
```{r, eval = TRUE, echo = FALSE}
fluidPage(
textInput(inputId = "custom_text", label = "Input some text here:"),
strong("Text is shown below:"),
textOutput(outputId = "user_text")
)
```
\#`{r, context = "server", eval = TRUE} # output$user_text <- renderText({ input$custom_text }) #`
------------------------------------------------------------------------
The code for this app is given below, with a few pieces missing (indicated with `___`). Each of the blanks are numbered, e.g. (`[1]`, `[2]`, etc.)
```{r eval = FALSE, echo = TRUE}
library(shiny)
ui <- fluidPage(
textInput(
inputId = "custom_text",
label = "_[1]_"
),
strong("Text is shown below:"),
_[2]_(outputId = "_[3]_")
)
server <- function(input, output, session){
output$user_text <- renderText({ input$_[4]_ })
}
shinyApp(ui = ui, server = server)
```
\#`` {r mc-2} #question("Which of the following is false?", # answer('`[1]` should be `"Input some text here:"`', # message = "Take a look at the app, what text is #shown to the user above the text input area?"), # answer('`[2]` should be `textOutput`', # message = "Check out the Shiny cheatsheet for pairs #of input and output functions"), # answer('`[3]` should be `"custom_text"`', correct = TRUE), # answer('`[4]` should be `"custom_text"`', # message = "What is the ID of the input that should #be rendered?"), # allow_retry = TRUE #) # ``
### Reactivity
Let's also briefly discuss reactivity.
```{r, out.width = "80%"}
knitr::include_graphics("images/reactivity.png")
```
It's easy to build interactive applications with Shiny, but to get the most out of it, you'll need to understand the reactive programming scheme used by Shiny.
In a nutshell Shiny automatically updates outputs, such as plots, when inputs that go into them change.
### Putting all the pieces together
Before we wrap up this section, I should also mention the last component of each Shiny app, which is a call to the aptly named `shinyApp()` function, which puts the UI and the server pieces together to create a Shiny app object.
```{r, out.width = "80%"}
knitr::include_graphics("images/shinyAppfunction.png")
```
Time to put this all into practice!
### Practice: Rules of server functions
Which of the following is not true about server functions?
\#`` {r mc-3} #question("Which of the following is not true about server functions?", # answer("Server functions should include a call to #`runApp()`", # correct = TRUE, # message = "The `runApp()` function can be used in the Console to run a Shiny application, as an alternative to the Run App button in the RStudio IDE." # ), # answer("Objects to be displayed should be saved to #`output$`"), # answer("Reactive objects should be built with `render*()` functions"), # answer("Input values should be referred to with `input$`"), # allow_retry = TRUE, # random_answer_order = TRUE #) # ``
### Practice: Fix it up
Below is the code for the Shiny app we built earlier, however currently the code is broken. Specifically there are errors in the definition of the server function as well as in the `mainPanel` of the UI.
#### Your turn
- Review the app and identify errors in the code.
- Hint: Refer back to the rules of server functions.
- Do the render functions match the output functions? If not, make the appropriate change and try running the app. Are there any remaining errors?
- Are the inputs referred to using the correct syntax? If not, make the appropriate change and try running the app. Are there any remaining errors?
- Are the outputs referred to using the correct names? If not, make the appropriate change and try running the app. Are there any remaining errors?
::: proj
*Navigate to the project called **1-3 Fix it up** after clicking the button below*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Workspace](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-1-3-fixup, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
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"
),
# Select variable for x-axis
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"
),
# Select variable for color
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"
)
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterPlot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderTable({
ggplot(data = movies, aes_string(x = x, y = y, color = z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
```{r ex-1-3-fixup-solution, include = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
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"
),
# Select variable for x-axis
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"
),
# Select variable for color
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"
)
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y, color = input$z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
## Recap
Let's quickly recap what we have learned in this chapter.
###
Every Shiny app has a webpage that the user visits, and behind this webpage there is a computer that serves this webpage by running R.
```{r, out.width = "80%"}
knitr::include_graphics("images/recap-1.png")
```
###
When running your app locally, the computer serving your app is your computer.
```{r, out.width = "80%"}
knitr::include_graphics("images/recap-2.png")
```
###
When your app is deployed, the computer serving your app is a web server.
```{r, out.width = "80%"}
knitr::include_graphics("images/recap-3.png")
```
###
Each app is comprised of two components, a UI and a server.
```{r, out.width = "80%"}
knitr::include_graphics("images/recap-4.png")
```
- The UI is ultimately built with HTML, CSS, and JavaScript. However, you as the Shiny developer do not need to know these languages. Shiny lets R users write user interfaces using a simple, familiar-looking API. However there are no limits to customization for advanced users who are familiar with these languages.
- The server function contains the instructions to map user inputs to outputs.
I often think of the UI as containing syntax specific to Shiny, and the server as containing R code you might already be familiar with -- with some Shiny functions added to achieve reactivity.
### Tip: Change display
In this tutorial you will be developing your apps in RStudio Cloud projects, but once you're done with the tutorial you might consider developing your apps in the RStudio IDE, which has some some handy-dandy functionality for running and viewing your apps.
RStudio will automatically recognize R scripts that contain `ui` and `server` components and that end with a call to the `shinyApp()` function and will make available the Run App button. You can choose to run your app in a new window, or in the viewer pane of your RStudio window.
```{r, out.width = "80%"}
knitr::include_graphics("images/recap-5.png")
```
### Tip: Close an app
When you are done with an app, you can terminate the session by clicking the red stop button in your viewer pane.
```{r, out.width = "80%"}
knitr::include_graphics("images/recap-6.png")
```
###
That's all for this module! In the next module we discuss inputs, outputs, and rendering functions in further detail.