1
1
library(plotly )
2
2
library(shiny )
3
3
4
- # compute a correlation matrix
4
+ # cache computation of a correlation matrix
5
5
correlation <- round(cor(mtcars ), 3 )
6
- nms <- names(mtcars )
7
6
8
7
ui <- fluidPage(
9
8
mainPanel(
@@ -14,15 +13,22 @@ ui <- fluidPage(
14
13
)
15
14
16
15
server <- function (input , output , session ) {
16
+
17
17
output $ heat <- renderPlotly({
18
- plot_ly(x = nms , y = nms , z = correlation ,
19
- key = correlation , type = " heatmap" , source = " heatplot" ) %> %
20
- layout(xaxis = list (title = " " ),
21
- yaxis = list (title = " " ))
18
+ plot_ly(source = " heatmap" ) %> %
19
+ add_heatmap(
20
+ x = names(mtcars ),
21
+ y = names(mtcars ),
22
+ z = correlation
23
+ ) %> %
24
+ layout(
25
+ xaxis = list (title = " " ),
26
+ yaxis = list (title = " " )
27
+ )
22
28
})
23
29
24
30
output $ selection <- renderPrint({
25
- s <- event_data(" plotly_click" , source = " heatplot " )
31
+ s <- event_data(" plotly_click" , source = " heatmap " )
26
32
if (length(s ) == 0 ) {
27
33
" Click on a cell in the heatmap to display a scatterplot"
28
34
} else {
@@ -32,20 +38,23 @@ server <- function(input, output, session) {
32
38
})
33
39
34
40
output $ scatterplot <- renderPlotly({
35
- s <- event_data(" plotly_click" , source = " heatplot" )
36
- if (length(s )) {
37
- vars <- c(s [[" x" ]], s [[" y" ]])
38
- d <- setNames(mtcars [vars ], c(" x" , " y" ))
39
- yhat <- fitted(lm(y ~ x , data = d ))
40
- plot_ly(d , x = ~ x ) %> %
41
- add_markers(y = ~ y ) %> %
42
- add_lines(y = ~ yhat ) %> %
43
- layout(xaxis = list (title = s [[" x" ]]),
44
- yaxis = list (title = s [[" y" ]]),
45
- showlegend = FALSE )
46
- } else {
47
- plotly_empty()
48
- }
41
+ clickData <- event_data(" plotly_click" , source = " heatmap" )
42
+ if (is.null(clickData )) return (NULL )
43
+
44
+ # get the clicked x/y variables and fit model to those 2 vars
45
+ vars <- c(clickData [[" x" ]], clickData [[" y" ]])
46
+ d <- setNames(mtcars [vars ], c(" x" , " y" ))
47
+ yhat <- fitted(lm(y ~ x , data = d ))
48
+
49
+ # scatterplot with fitted line
50
+ plot_ly(d , x = ~ x ) %> %
51
+ add_markers(y = ~ y ) %> %
52
+ add_lines(y = ~ yhat ) %> %
53
+ layout(
54
+ xaxis = list (title = clickData [[" x" ]]),
55
+ yaxis = list (title = clickData [[" y" ]]),
56
+ showlegend = FALSE
57
+ )
49
58
})
50
59
51
60
}
0 commit comments