-
Notifications
You must be signed in to change notification settings - Fork 41
/
07-graphics.Rmd
388 lines (289 loc) · 11.5 KB
/
07-graphics.Rmd
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
# Graphics
**Learning objectives**
- Use `renderPlot()` to display reactive plots.
- Create interactive plots.
- Display images with `renderImage()`.
## Interactivity: the basics
```{r 07-01, message=FALSE, warning=FALSE, paged.print=FALSE}
library(shiny)
library(ggplot2)
```
The syntax for displaying a plot in a Shiny app is:
In the **UI** the `plotOutput()` function releases an output that can also be an input.
In the server the `renderPlot()` function releases the plot.
### Summary of interactive action events
- `click`
- `dblclick`: (double click)
- `hover`: (when the mouse stays in the same place for a little while)
- `brush`: (a rectangular selection tool)
#### Clicking
As we see in this example, there are two options available:
- `"plot_click"`
- `nearPoints()`
The first option allows you to select specific points from the data, the other one select the area around the selected point, so it releases values which are near the observed value.
```{r 07-02,eval=FALSE, message=FALSE, warning=FALSE, include=T, paged.print=FALSE}
ui <- fluidPage(
plotOutput("plot", click = "plot_click", brush = "plot_brush"),
verbatimTextOutput("info"),
tableOutput("data")
)
server <- function(input, output, session) {
output$plot <-
renderPlot({
plot(mtcars$wt, mtcars$mpg)
}, res = 96)
output$info <-
renderPrint({
# this is to make sure the app does nothing before the first click
req(input$plot_click)
x <- round(input$plot_click$x, 1)
y <- round(input$plot_click$y, 1)
cat("[", x, ", ", y, "]", sep = "")
})
output$data <-
renderTable({
req(input$plot_click)
# browser() (you need to use the function with all options as is)
# nearPoints() function translates coords to data
nearPoints(mtcars, input$plot_click, xvar = "wt", yvar = "mpg")
# brushedPoints(mtcars, input$plot_brush, xvar = "wt", yvar = "mpg")
})
output$data <-
renderTable({
req(input$plot_click)
brushedPoints(mtcars, input$plot_brush, xvar = "wt", yvar = "mpg")
})
}
# shinyApp(ui,server)
```
More specific example here : https://gallery.shinyapps.io/095-plot-interaction-advanced/
#### Brushing
- brush: a rectangular selection
Example of a [Brushed Points App](https://hadley.shinyapps.io/ms-brushedPoints)
```{r 07-03,eval=FALSE, include=T}
ui <- fluidPage(
plotOutput("plot", brush = "plot_brush"),
tableOutput("data")
)
server <- function(input, output, session) {
output$plot <- renderPlot({
# here we change the plot() function with ggplot()
ggplot(mtcars, aes(wt, mpg)) + geom_point()
}, res = 96)
output$data <- renderTable({
brushedPoints(mtcars, input$plot_brush)
})
}
```
## Modifying the plot
- `reactiveVal()`
- `reactive()`
see more info in [chapter 16 Escaping the graph](https://mastering-shiny.org/reactivity-components.html)
This is part of the **function factories** (more info here: [Function factories](https://adv-r.hadley.nz/function-factories.html)), i.e. a function that makes functions. This is the main difference with `reactive()`, the `reactiveVal()` function updates the values.
It need to be run in an reactive environment. If you'd like to debug the function you can use `browser()` inside the app, as we shown before.
```{r 07-04,eval=FALSE, include=T}
val <- reactiveVal(10)
val()
```
Let's see the distance between a click and the points: [Modifying Size App]( https://hadley.shinyapps.io/ms-modifying-size)
```{r 07-05,eval=FALSE, include=T}
set.seed(1014)
df <- data.frame(x = rnorm(100), y = rnorm(100))
ui <- fluidPage(
plotOutput("plot", click = "plot_click") # comma
)
server <- function(input, output, session) {
# the reactiveVal function
dist <- reactiveVal(rep(1, nrow(df)))
# and the observeEvent calling the reactivity
observeEvent(input$plot_click,
dist(nearPoints(df,
input$plot_click,
allRows = TRUE,
addDist = TRUE)$dist_) # this "dist_" gives the distance between the row and the event (in pixels)
)
output$plot <- renderPlot({
df$dist <- dist()
ggplot(df, aes(x, y, size = dist)) +
geom_point() +
# set the limits
scale_size_area(limits = c(0, 1000), max_size = 10, guide = NULL)
}, res = 96)
}
# shinyApp(ui,server)
```
Another example with different colors:
- initialise the `reactiveVal()` to a vector of FALSEs
- use `brushedPoints()` and `|` to add any points under the brush to the selection
- double clicking reset the selection
```{r 07-06,eval=FALSE, include=T}
ui <- fluidPage(
plotOutput("plot", brush = "plot_brush", dblclick = "plot_reset")
)
server <- function(input, output, session) {
selected <-
reactiveVal(rep(FALSE, nrow(mtcars)))
observeEvent(input$plot_brush, {
brushed <- brushedPoints(mtcars,
input$plot_brush,
# "selected_" whether it’s near the click event
allRows = TRUE)$selected_
selected(brushed | selected())
})
observeEvent(input$plot_reset, {
selected(rep(FALSE, nrow(mtcars)))
})
output$plot <- renderPlot({
mtcars$sel <- selected()
ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(colour = sel)) +
scale_colour_discrete(limits = c("TRUE", "FALSE"))
}, res = 96)
}
# shinyApp(ui,server)
```
## Interactivity limitations
The basic data flow in interactive plots:
```{r 07-07,echo=FALSE,fig.align="center",fig.dim="100%"}
DiagrammeR::mermaid(
"graph TB
A(JavaScript captures the mouse event)-->B(Shiny sends the mouse event data back to R)
B-->C(The reactive actions are recomputed)
C-->D(plotOutput send an image of the results to the browser)
"
)
```
In terms of limitations, here we talk about **time response**. To achieve what is thought to be **instantaneous** reaction at click, such as the requested modification is immediately visible, it would be necessary to improve JavaScript computation. And this can be obtained to the **plotly package**.
Here is the resource: [Interactive web-based data visualization with R, plotly, and shiny](https://plotly-r.com/)
## Dynamic height and width
How to change the plot size interactively?
see this example: https://hadley.shinyapps.io/ms-resize
```{r 07-08}
ui <- fluidPage(
sliderInput("height", "height", min = 100, max = 500, value = 250),
sliderInput("width", "width", min = 100, max = 500, value = 250),
plotOutput("plot", width = 250, height = 250)
)
server <- function(input, output, session) {
output$plot <- renderPlot(
width = function() input$width,
height = function() input$height,
res = 96,
{
plot(rnorm(20), rnorm(20))
}
)
}
# shinyApp(ui,server)
```
## Images
To display images use `renderImage()` as in this app: https://hadley.shinyapps.io/ms-puppies.
```{r 07-09}
puppies <- tibble::tribble(
~breed, ~ id, ~author,
"corgi", "eoqnr8ikwFE","alvannee",
"labrador", "KCdYn0xu2fU", "shaneguymon",
"spaniel", "TzjMd7i5WQI", "_redo_"
)
ui <- fluidPage(
selectInput("id", "Pick a breed",
choices = setNames(puppies$id, puppies$breed)),
htmlOutput("source"),
imageOutput("photo")
)
server <- function(input, output, session) {
output$photo <- renderImage({
list(
src = file.path("puppy-photos", paste0(input$id, ".jpg")),
contentType = "image/jpeg",
width = 500,
height = 650
)
}, deleteFile = FALSE)
output$source <- renderUI({
info <- puppies[puppies$id == input$id, , drop = FALSE]
HTML(glue::glue("<p>
<a href='https://unsplash.com/photos/{info$id}'>original</a> by
<a href='https://unsplash.com/@{info$author}'>{info$author}</a>
</p>"))
})
}
```
More info here: https://shiny.rstudio.com/articles/images.html
## Resources
- [Shiny cheatsheet](https://shiny.rstudio.com/images/shiny-cheatsheet.pdf)
- [Images](https://shiny.rstudio.com/articles/images.html)
## Presentation Cohort 1
Follow this link to the presentation for this chapter:
```{r test, echo=FALSE}
knitr::include_url("https://masteringshinych7.netlify.app/#1")
```
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/UsE8-qBciDo")`
<details>
<summary> Meeting chat log </summary>
```
00:09:09 Russ Hyde: Hi everyone.
00:09:19 Layla Bouzoubaa: 👋🏼
00:36:50 priyanka gagneja: thanks this is awesome .. i had been looking to make this kind of progress bar .. I tired a few things but they were not so pretty
00:37:28 Russ Hyde: The website for waiter is really sweet: https://waiter.john-coene.com/#/
00:48:16 Andrew Bates: https://stackoverflow.com/questions/44112000/move-r-shiny-shownotification-to-center-of-screen
00:50:27 Russ Hyde: There might be other notification approaches: https://github.com/dreamRs/shinypop
```
</details>
### Cohort 2
`r knitr::include_url("https://www.youtube.com/embed/W01MoW3AWpY")`
<details>
<summary> Meeting chat log </summary>
```
00:21:58 shane: https://rstudio.github.io/thematic/
00:25:03 Collin Berke: https://bootswatch.com/
00:28:50 Conor Tompkins: "This works because, at plot time, thematic grabs CSS styles from the plot(s) HTML container (via shiny::getCurrentOutputInfo())1 and uses that info to set new R styling defaults."
00:28:56 Conor Tompkins: From https://rstudio.github.io/thematic/articles/auto.html#shiny
00:31:15 Collin Berke: Not sure how this relates, but here is the link to the `theme_set()` function I referenced: https://ggplot2.tidyverse.org/reference/theme_get.html
00:46:41 Collin Berke: You can also see the object here: https://gallery.shinyapps.io/095-plot-interaction-advanced/
00:50:48 Collin Berke: Here's some more about subsetting list objects. Check out this chapter from Advanced R: https://adv-r.hadley.nz/subsetting.html
01:13:14 Ryan Metcalf: https://www.osti.gov/servlets/purl/1115145
```
</details>
### Cohort 3
`r knitr::include_url("https://www.youtube.com/embed/KwUE61NVDUk")`
<details>
<summary>Meeting chat log</summary>
```
00:46:29 Njoki Njuki Lucy: Sorry to ask; what is the reactive
00:46:44 Njoki Njuki Lucy: reactiveVal() doing here? I am lost
00:57:28 Ryan Metcalf: "res" in the explanation is the size or scale relation / ratios between your x and y. In this case, 96 pixels is the relationship between height and width.
00:58:18 Ryan Metcalf: Or maybe a better way to convey resolution is how “zoomed in" or “zoomed out" your graphical object is rendered.
00:58:41 Njoki Njuki Lucy: Thank you, Ryan! :)
01:01:38 Njoki Njuki Lucy: what would be the importance of having dynamic height and width?
01:09:49 Federica Gazzelloni: https://shiny.rstudio.com/articles/images.html
01:11:43 Oluwafemi Oyedele: Thank you!!!
```
</details>
### Cohort 4
`r knitr::include_url("https://www.youtube.com/embed/Zq6z00X3jzM")`
<details>
<summary>Meeting chat log</summary>
```
00:11:01 LUCIO ENRIQUE CORNEJO RAMÍREZ: hello
00:11:11 Lydia Gibson: Hi Lucio!
00:11:56 Lydia Gibson: Trevin won’t be able to join today, but I believe Matthew will be.
00:12:12 Lydia Gibson: Let’s give him a couple more minutes
00:35:47 Lydia Gibson: https://shiny.rstudio.com/gallery/plot-interaction-advanced.html
00:40:58 Lydia Gibson: https://plotly-r.com/index.html
00:41:17 LUCIO ENRIQUE CORNEJO RAMÍREZ: mmm not really, it was pretty clear
00:41:19 LUCIO ENRIQUE CORNEJO RAMÍREZ: cool demos
00:41:50 LUCIO ENRIQUE CORNEJO RAMÍREZ: I' bee presenting next week
00:41:53 LUCIO ENRIQUE CORNEJO RAMÍREZ: thank you, bye
```
</details>
### Cohort 5
`r knitr::include_url("https://www.youtube.com/embed/URL")`
<details>
<summary>Meeting chat log</summary>
```
LOG
```
</details>