-
Notifications
You must be signed in to change notification settings - Fork 2
/
16-shiny.qmd
637 lines (483 loc) · 20.1 KB
/
16-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
# Graphical interfaces with Shiny
You have had a preview of a `shiny` interface in the previous section with the interactive parameter input in a Rmarkdown file.
Using the `shiny` package, you can actually easily build an interactive graphical user interface (GUI) in which you will be able to set parameters (values, files...), visualize the outputs (plots, images, tables...), and write files as output. This is very useful when you have to always repeat the same task with a varying input parameter, for example.
## Stand-alone shiny application
A shiny application is an `app.R` file (it must be named like that) containing 3 elements:
1. `ui`: definition of the interface layout (where are the buttons, text input, plot output, etc.) and the input parameters
2. `server`: definition of the various actions to perform with the input parameters
3. `shinyApp(ui, server)`{.R}: launches the shiny app with the above defined parameters
In Rstudio, create a new "Shiny web app". It will create an `app.R` file containing this:
```r
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)
```
Run it by clicking "Run App": a window opens and you can pan the slider and see the resulting output.
In case you want to clean up the code, you can separate `app.R` into `ui.R` and `server.R`. No need to add the `shinyApp(ui = ui, server = server)`{.R} line in that case.
All user-defined functions and variable definitions can be defined in a `global.R` file that will be sourced by default when launching the app.
### The layout
In the `ui <- fluidPage(...)`{.R} item, you define the layout of your application. In the above example:
- `titlePanel("Title")`{.R} creates a title
- `sidebarLayout()`{.R} separates the layout in a short one on the left (`sidebarPanel()`{.R}) and a main one on the right (`mainPanel()`{.R})
- `sliderInput("name_of_slider", "text to display", min=min_value, max=max_value,`{.R} `value=current_value, step=step_value)` creates a slider to input a value. This value will be retrieved by `input$name_of_slider`{.R} in the `server()`{.R} function.
- `plotOutput("name_of_plot")`{.R} plots the result of `output$name_of_plot`{.R} defined in the `server()`{.R} function.
See the [guide to application layout](https://shiny.rstudio.com/articles/layout-guide.html) for more layout options. I also recommend taking a look at the packages [`shinydashboard`](https://rstudio.github.io/shinydashboard/get_started.html) and [`shinymaterial`](https://github.com/ericrayanderson/shinymaterial).
### The server
In the `server <- function(input, output){...}`{.R} function, you define the various actions and outputs in reaction to an input change.
In the above example, we define `output$distPlot`{.R} as a `renderPlot()`{.R} function whose results depends on `input$bins`{.R}. The plot is rendered in the `ui` by `plotOutput("distPlot")`{.R}.
### Various useful functions
<!-- MarkdownTOC -->
- [Input](#input)
- [Buttons](#buttons)
- [Checkbox](#checkbox)
- [Text/numeric](#textnumeric)
- [Slider](#slider)
- [File](#file)
- [Dropdown menu](#dropdown-menu)
- [Output](#output)
- [Display a plot](#display-a-plot)
- [Display text](#display-text)
- [Display a table](#display-a-table)
- [Reactive events](#reactive-events)
- [Writing a file](#writing-a-file)
<!-- /MarkdownTOC -->
<a id="input"></a>
#### Input
<a id="buttons"></a>
##### Buttons
```r
# # # # # # # # #
# In ui:
actionButton("button_name", "Text to display")
# # # # # # # # #
# In server:
observeEvent(input$button_name, {
# do something
})
# or
some_function <- eventReactive(input$button_name, {
# do something
})
```
##### Checkbox
```r
# # # # # # # # #
# In ui:
checkboxInput("checkbox_name", "Text to display", value=FALSE)
# # # # # # # # #
# In server:
input$checkbox_name #TRUE or FALSE
```
<a id="textnumeric"></a>
##### Text/numeric
```r
# # # # # # # # #
# In ui:
textInput("text_name",
label = "Text to display",
value = "initial value",
width = '100%')
textAreaInput("text_name",
label="Text to display",
value = "initial_value",
rows = 5) %>%
shiny::tagAppendAttributes(style = 'width: 100%;')
numericInput("value_name", 'Text to display', value=0)
# # # # # # # # #
# In server, retrieve it as:
input$text_name
input$value_name
```
<a id="slider"></a>
##### Slider
```r
# # # # # # # # #
# In ui:
sliderInput("slider_name", "Text to display",
min = 1,
max = 50,
step= 1,
value = 30)
# # # # # # # # #
# In server, retrieve it as:
input$slider_name
```
<a id="file"></a>
##### File
```r
# # # # # # # # #
# In ui:
fileInput("file_in",
"Choose input file:", accept = c(".txt")
)
# # # # # # # # #
# In server, retrieve it as:
input$file_in$datapath
# For example, read it as a data.frame with myData():
myData <- reactive({
inFile <- input$file_in
if (is.null(inFile)) {
return(NULL)
} else {
return(read.table(inFile$datapath, header=TRUE))
}
})
```
<a id="dropdown-menu"></a>
##### Dropdown menu
```r
# # # # # # # # #
# In ui:
selectInput("menu_name", "Text to display",
choices=c("choice 1", "choice 2"),
multiple = FALSE # multiple selection possible
)
# # # # # # # # #
# In server, retrieve it as:
input$menu_name
```
<a id="output"></a>
#### Output
<a id="display-a-plot"></a>
##### Display a plot
```r
# # # # # # # # #
# In ui:
plotOutput("plot_name", height = 600,
click = "plot_click", # to retrieve the click position
dblclick = "plot_dblclick", # to retrieve the double click position
hover = "plot_hover", # to retrieve the mouse position
brush = "plot_brush" # to retrieve the rectangle coordinates
)
# # # # # # # # #
# In server:
output$plot_name <- renderPlot({
# do plot:
plot(...)
# or
ggplot(...)
})
```
If you want an interactive plot, use `plotlyOutput()`{.R} and `renderPlotly()`{.R} instead.
<a id="display-text"></a>
##### Display text
```r
# # # # # # # # #
# In ui:
textOutput("text_to_display")
# Verbatim text (fixed width characters):
verbatimTextOutput("text_to_display")
# # # # # # # # #
# In server:
output$text_to_display <- renderText({ "some text" })
output$text_to_display <- renderPrint({ "some text" })
```
<a id="display-a-table"></a>
##### Display a table
```r
# # # # # # # # #
# In ui:
tableOutput("table_to_display")
# # # # # # # # #
# In server:
output$table_to_display <- renderTable({ df })
```
Or in case you want interactive tables, use the package [datatable](https://shiny.rstudio.com/articles/datatables.html):
```r
library(DT)
# # # # # # # # #
# In ui:
dataTableOutput("table_to_display")
# # # # # # # # #
# In server:
output$table_to_display <- renderDataTable({ df })
```
<a id="reactive-events"></a>
##### Reactive events
In case you want the plots or text display to react to a change in input value, you can wrap the corresponding code in the `reactive()`{.R} function on the server side:
```r
# # # # # # # # #
# In ui:
fileInput("file_in",
"Choose input file:", accept = c(".txt")
),
checkboxInput("header", "Header?", value=TRUE),
selectInput("menu", "Columns to display",
choices=1, selected = 1, multiple = TRUE),
tableOutput("table")
# # # # # # # # #
# In server:
myData <- reactive({
inFile <- input$file_in
if (is.null(inFile)) {
return(NULL)
} else {
df <- read.table(inFile$datapath, header=input$header)
updateSelectInput(session, "menu", choices=1:ncol(df), selected=input$menu)
return(df)
}
})
output$table <- renderTable( myData()[,sort(as.numeric(input$menu))] )
```
The various input default values can be updated using the following functions on the server side:
```r
# Dropdown menu
updateSelectInput(session, "menu_name", choices=new_choices)
# Text
updateTextInput(session, "text_name", value = new_value)
# Numeric
updateNumericInput(session, "value_name", value = new_value)
```
<a id="writing-a-file"></a>
##### Writing a file
This is not a function of shiny, but you may want to write a text file. If this comes from a `data.frame`{.R}, you can use the function `write.table()`{.R}:
```r
df <- data.frame(x=1:10,y=sin(1:10))
write.table(df, "test.dat", quote=FALSE, row.names=FALSE)
```
For other forms of printing, look into the `write()`{.R} function:
```r
toprint <- paste("hello", "world")
outfile <- file("file_name.txt", encoding="UTF-8")
write(toprint, file=outfile)
close(outfile)
```
You can for example write a Rmd file that you will render (as pdf, etc...) using [`render()`{.R}](https://www.rdocumentation.org/packages/rmarkdown/versions/1.13/topics/render):
```r
rmarkdown::render("file_name.Rmd")
```
<a id="example"></a>
### Example {#example-shiny}
Create a new shiny app with the following code, and play around with it. The input file should be the tidy <a href="Data/population.txt" download target="_blank">population.txt</a>.
```r
library(shiny)
library(tidyverse)
library(plotly)
library(DT)
ui <- fluidPage(
titlePanel("City population in France"),
sidebarLayout(
sidebarPanel(
fileInput("file_in", "Choose input file:",
accept = c(".txt") ),
selectInput("sel_city", "City:", choices = "", multiple = TRUE)
),
mainPanel(
tabsetPanel(
tabPanel("Plot", plotlyOutput("cityplot", height = "400px")),
tabPanel("Table", dataTableOutput("table"))
)
)
)
)
server <- function(input, output, session) {
# myData() returns the data if a file is provided
myData <- reactive({
inFile <- input$file_in
if (is.null(inFile)) {
return(NULL)
} else {
df <- read.table(inFile$datapath, header=TRUE)
# in case something changes,
# update the city input selection list
updateSelectInput(session, "sel_city",
choices = unique(df$city),
selected = unique(df$city)[1])
return(df)
}
})
# plot the pop vs year for the selected cities
output$cityplot <- renderPlotly({
df <- myData()
if(is.null(df)) return(NULL)
p <- df %>%
filter(city %in% input$sel_city) %>%
ggplot(aes(x=year, y=pop, size=pop, color=city)) +
geom_point() +
geom_smooth(method="lm", alpha=0.1,
show.legend = FALSE,
aes(fill=city)) +
ggtitle(paste0("Population in ",
paste(input$sel_city, collapse = ", ")
))+
labs(x="Year", y="Population")+
theme_light()
ggplotly(p, dynamicTicks = TRUE)
})
# show data as a table
output$table <- renderDataTable({
df <- myData() %>% filter(city %in% input$sel_city)
if(is.null(df)) return(NULL)
df <- pivot_wider(df, names_from=year, values_from=pop)
datatable(df, rownames = FALSE)
})
}
shinyApp(ui = ui, server = server)
```
This will render [like this](https://cbousige.shinyapps.io/shiny_example/).
<a id="rmarkdown-embedded-shiny-application"></a>
## Rmarkdown-embedded shiny application
A shiny application can even be embedded inside a Rmarkdown document by providing `runtime: shiny` in the YAML header. A short example here, try to compile it:
````markdown
---
title: "Test"
output: html_document
runtime: shiny
---
This is a test Rmarkdown document.
`r ''````{r, echo=FALSE, message=FALSE}
library(ggplot2)
library(plotly)
df <- read.table("Data/population.txt", header=TRUE)
shinyApp(
ui = fluidPage(
selectInput("city", "City:", choices = unique(df$city)),
plotlyOutput("cityplot", height = 600)
),
server = function(input, output) {
output$cityplot = renderPlotly({
p <- ggplot(data=subset(df,city==input$city),
aes(x=year, y=pop, size=pop)) +
geom_point() +
geom_smooth(method="lm", alpha=0.1, show.legend = FALSE) +
ggtitle(paste("Population in ",input$city,sep=""))+
labs(x="Year", y="Population")+
theme_light()
ggplotly(p)
})
}
)
```
````
The only "problem" with this solution is that the html file that is produced will not run the shiny app by itself, you have to open the Rmd file in Rstudio and hit "Run Document".
Another solution consists in deploying your app on [shinyapps.io](https://www.shinyapps.io/) and embedding the page in your document with:
````r
`r ''````{r, echo=FALSE}
knitr::include_app("https://cbousige.shinyapps.io/shiny_example/",
height = "800px")
```
````
<a id="deploying-your-shiny-app"></a>
## Deploying your shiny app
There are 4 ways to deploy your app: passing the `app.R` file to your users, deploying to [shinyapps.io](https://www.shinyapps.io/), deploying on your own server, or building an executable with Electron.
<a id="passing-the-appr-file-to-your-users"></a>
### Passing the app.R file to your users
This option is certainly easy: just send your `app.R` file (or Rmd file with shiny embedded app) as well as any other files needed (*e.g.* `global.R`) to your users, explain to them how to run it, and *voilà*.
However, this needs a little bit of know-how from the users: they need to install R and Rstudio, install the needed packages, and run the app.
A good option to remove the "package-installing" step is to define a function `check.package()`{.R} that will check if the package is installed, install it if needed, and load it:
```r
check.packages <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
# Usage:
check.packages("ggplot2")
```
<a id="deploying-to-shinyappsio"></a>
### Deploying to shinyapps.io
Applications deployed on shinyapps.io will be accessible from anywhere through a weblink. See for example [my application](https://cbousige.shinyapps.io/rubypressure/) to determine the pressure from a ruby Raman spectrum or the expected Raman shift for a given pressure and laser wavelength. Your application will however be public and you will have some limitations in the number of online applications and time of use (if you don't pay a fee, see [here](https://www.shinyapps.io/) for the various plans).
- First, create an account on [shinyapps.io](https://www.shinyapps.io/admin/#/signup)
- Follow the steps described [here](https://docs.rstudio.com/shinyapps.io/getting-started.html#deploying-applications) to:
+ *Configure RSconnect*: in your shinyapps.io dashboard, click your name, then Tokens, and create a token for a new app. Copy the text in the popup window.
+ *Deploy the app* from the Rstudio window by clicking on the "Publish" button in the top right corner of the interface. Follow the steps along the *shinyapps.io* way.
Note that in that case, you should not have any `install.package()`{.R} command in your code. Most packages are supported by shinyapps.io.
<a id="deploying-on-your-own-linux-server"></a>
### Deploying on your own Linux server
This option is more advanced and I'm not going into details for that, but you have a number of tutorials online. See *e.g.* [here](https://shiny.rstudio.com/articles/shiny-server.html), [here](https://docs.rstudio.com/shiny-server/) or [here](https://www.digitalocean.com/community/tutorials/how-to-set-up-shiny-server-on-ubuntu-16-04).
You might consider this option if you work in a company that want to handle privately its data (which sounds plausible) and not pay the shinyapps.io fee to password protect the app. In that case, just work with the IT department to get it running.
<a id="building-an-executable"></a>
### Building an executable
On **Windows**, there is this possibility that looks nice but that I never tried because I don't have Windows: [RInno](https://ficonsulting.github.io/RInno/).
On **any platform**: there is the possibility described [here](https://www.youtube.com/watch?v=ARrbbviGvjc) with the corresponding [github page](https://github.com/ColumbusCollaboratory/electron-quick-start). This option is actually awesome and a quite recent possibility. However, since the produced application will contain R and the needed packages, the executable file is quite heavy.
<a id="further-reading"></a>
## Further reading
- The Shiny [cheatsheet](https://shiny.rstudio.com/images/shiny-cheatsheet.pdf)
- Help on [deploying your shiny app](https://shiny.rstudio.com/tutorial/written-tutorial/lesson7/)
- [Guide to application layout](https://shiny.rstudio.com/articles/layout-guide.html)
- The [Shiny Gallery](https://shiny.rstudio.com/gallery/): find what you want to do and adapt it to your needs
- The official [Shiny video tutorial](https://shiny.rstudio.com/tutorial/)
<a id="exercises"></a>
## Exercises {#exo-shiny}
<details>
<summary>**Exercise 1**</summary>
- Create a new empty app with a blank user-interface and run it.
- Add a title, a left panel and a main panel
- Add an input numerical value defaulting to 1 and with a step of 0.05, name it "bw"
- Add a slider input from 0 to 1e3 by steps of 1e2 defaulting to 5e2, name it "N_val"
- Add a plot of the `density` of `rnorm(N_val)`{.R} with bandwidth `bw`
- Make sure `bw>0`, otherwise don't produce the plot
<details>
<summary>Solution</summary>
```r
library(shiny)
ui <- fluidPage(
titlePanel("Some title"),
sidebarLayout(
sidebarPanel(
numericInput("bw", "Enter bandwidth:", 1, step=0.05),
sliderInput("N_val", "Number of points:",
min = 0, max = 1e4, step= 1e2, value = 5e2)
),
mainPanel(
plotOutput("plot", height = 600)
)
)
)
server <- function(input, output, session) {
output$plot <- renderPlot({
if(input$bw==0) return(NULL)
plot(density(rnorm(input$N_val), bw=abs(input$bw)))
})
}
shinyApp(ui = ui, server = server)
```
</details>
</details>
<details>
<summary>**Exercise 2**</summary>
Create a shiny application that will:
- read an input (through a file dialog) Raman spectrum from a ruby (<a href="Data/data_xp/xpdata.zip" download target="_blank">XPdata.zip</a>)
- fit the data by two Lorentzians
- plot the data interactively
- ask for the laser wavelength as an input and give 568.189 nm as default
- write the corresponding pressure on the page using the `Pruby()`{.R} function defined in `myfunc.R` found in <a href="Data/XPdata.zip" download target="_blank">XPdata.zip</a>.
- insert a button that will, when pressed, render a pdf report displaying the laser wavelength, the plot, the fit and the pressure found:
+ write a separate Rmd file with the proper parameters
+ render the Rmd file as a pdf (see the `render()`{.R} function and [this help](https://shiny.rstudio.com/articles/generating-reports.html))
</details>
<br>
<br>
<br>
<br>
<br>