Skip to content

Instantly share code, notes, and snippets.

@cpsievert
Created October 29, 2019 21:39
Show Gist options
  • Save cpsievert/0965c8e4ac6a56d6d233de6ab0019cd2 to your computer and use it in GitHub Desktop.
Save cpsievert/0965c8e4ac6a56d6d233de6ab0019cd2 to your computer and use it in GitHub Desktop.
library(shiny)
mtcars$.key <- row.names(mtcars)
ui <- fluidPage(
  plotlyOutput("scatter"),
  plotlyOutput("bars")
)
server <- function(input, output, session) {
 
  data <- reactive({
    d <- event_data("plotly_selected", source = "scatter")
    mtcars$.color <- ifelse(mtcars$.key %in% d$customdata, "red", "black")
    mtcars
  })
 
  output$scatter <- renderPlotly({
    plot_ly(
      data(), x = ~wt, y = ~mpg,
      customdata = ~.key,
      color = ~I(.color),
      source = "scatter"
    ) %>%
      add_markers() %>%
      layout(dragmode = "lasso", showlegend = FALSE)
  })
 
  output$bars <- renderPlotly({
    ggplot(data(), aes(qsec, fill = .color, alpha = 0.1)) +
      geom_density() +
      scale_fill_identity() +
      theme(legend.position = "none")
  })
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment