|
| 1 | +library(shiny) |
| 2 | +library(ggplot2) |
| 3 | +library(dplyr) |
| 4 | +library(plotly) |
| 5 | + |
| 6 | +ui <- fluidPage( |
| 7 | + plotOutput("scatter1", brush = brushOpts("brush", direction = "xy")), |
| 8 | + plotlyOutput("plot1") |
| 9 | +) |
| 10 | + |
| 11 | +server <- function(input, output, session) { |
| 12 | + output$scatter1 <- renderPlot({ |
| 13 | + iris$selected <- 1 |
| 14 | + if (!is.null(input$brush)) { |
| 15 | + br <- input$brush |
| 16 | + x <- iris$Sepal.Length <= br$xmin | br$xmax <= iris$Sepal.Length |
| 17 | + y <- iris$Sepal.Width <= br$ymin | br$ymax <= iris$Sepal.Width |
| 18 | + iris$selected[x | y] <- 0.3 |
| 19 | + } |
| 20 | + ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species, alpha = selected)) + |
| 21 | + geom_point() + scale_alpha(guide = "none") |
| 22 | + }) |
| 23 | + |
| 24 | + output$plot1 <- renderPlotly({ |
| 25 | + p <- iris %>% |
| 26 | + count(Species) %>% |
| 27 | + plot_ly(x = Species, y = n, opacity = 0.5, type = "bar", |
| 28 | + marker = list(color = toRGB("grey92"))) %>% |
| 29 | + layout(barmode = "overlay", showlegend = FALSE) |
| 30 | + if (!is.null(input$brush)) { |
| 31 | + br <- input$brush |
| 32 | + s <- iris %>% |
| 33 | + filter(br$xmin <= Sepal.Length, Sepal.Length <= br$xmax) %>% |
| 34 | + filter(br$ymin <= Sepal.Width, Sepal.Width <= br$ymax) %>% |
| 35 | + count(Species) |
| 36 | + p <- add_trace(p, x = Species, y = n, data = s, |
| 37 | + marker = list(color = toRGB("steelblue"))) |
| 38 | + } |
| 39 | + p |
| 40 | + }) |
| 41 | +} |
| 42 | + |
| 43 | +shinyApp(ui, server) |
0 commit comments