Skip to content

Commit 503cafc

Browse files
committed
small improvements to shiny example apps
1 parent 55cc62a commit 503cafc

File tree

2 files changed

+31
-22
lines changed

2 files changed

+31
-22
lines changed

inst/examples/shiny/Diamonds/server.R

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ shinyServer(function(input, output, session) {
2121
facets <- paste(input$facet_row, '~', input$facet_col)
2222
if (facets != '. ~ .') p <- p + facet_grid(facets)
2323
# return the ggplot object and renderPlotly() will know how to handle it
24-
p
24+
toWebGL(p)
2525
})
2626

2727
})

inst/examples/shiny/event_data_click/app.R

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
library(plotly)
22
library(shiny)
33

4-
# compute a correlation matrix
4+
# cache computation of a correlation matrix
55
correlation <- round(cor(mtcars), 3)
6-
nms <- names(mtcars)
76

87
ui <- fluidPage(
98
mainPanel(
@@ -14,15 +13,22 @@ ui <- fluidPage(
1413
)
1514

1615
server <- function(input, output, session) {
16+
1717
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+
)
2228
})
2329

2430
output$selection <- renderPrint({
25-
s <- event_data("plotly_click", source = "heatplot")
31+
s <- event_data("plotly_click", source = "heatmap")
2632
if (length(s) == 0) {
2733
"Click on a cell in the heatmap to display a scatterplot"
2834
} else {
@@ -32,20 +38,23 @@ server <- function(input, output, session) {
3238
})
3339

3440
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+
)
4958
})
5059

5160
}

0 commit comments

Comments
 (0)