|
| 1 | +library(shiny) |
| 2 | +library(plotly) |
| 3 | +library(dplyr) |
| 4 | +library(MASS) |
| 5 | + |
| 6 | +kde_full <- with(diamonds, kde2d(carat, price)) |
| 7 | + |
| 8 | +ui <- fluidPage( |
| 9 | + plotlyOutput("bars", height = 300), |
| 10 | + plotlyOutput("heat") |
| 11 | +) |
| 12 | + |
| 13 | +server <- function(input, output, session) { |
| 14 | + |
| 15 | + output$bars <- renderPlotly({ |
| 16 | + plot_ly(diamonds, x = ~depth, source = "bars") %>% |
| 17 | + layout(dragmode = "select", selectdirection = "h") |
| 18 | + }) |
| 19 | + |
| 20 | + output$heat <- renderPlotly({ |
| 21 | + plot_ly() %>% |
| 22 | + add_heatmap(x = kde_full$x, y = kde_full$y, z = sqrt(t(kde_full$z))) |
| 23 | + }) |
| 24 | + |
| 25 | + observe({ |
| 26 | + brush <- event_data("plotly_brushing", source = "bars") |
| 27 | + p <- plotlyProxy("heat", session) |
| 28 | + |
| 29 | + # show full data if no brush exists |
| 30 | + if (is.null(brush)) { |
| 31 | + plotlyProxyInvoke(p, "restyle", "z", list(sqrt(t(kde_full$z)))) |
| 32 | + return() |
| 33 | + } |
| 34 | + |
| 35 | + d_filter <- filter(diamonds, between(depth, brush$x[1], brush$x[2])) |
| 36 | + if (nrow(d_filter) < 10) return() |
| 37 | + |
| 38 | + kde_filter <- with(d_filter, kde2d(carat, price)) |
| 39 | + |
| 40 | + plotlyProxyInvoke(p, "restyle", "z", list(sqrt(t(kde_filter$z)))) |
| 41 | + }) |
| 42 | + |
| 43 | +} |
| 44 | + |
| 45 | +shinyApp(ui, server) |
0 commit comments