Shiny App实现绘图选点自动弹出数据弹窗的技术问询
Automatically Display Brushed Points in a Shiny Modal
Let’s tweak your Shiny app so that when you brush points on the plot, a modal automatically pops up showing the selected data—no button clicks required. Here’s the updated code:
library(ggplot2) library(Cairo) # For nicer ggplot2 output when deployed on Linux library(shiny) mtcars2 <- mtcars[, c("mpg", "cyl", "disp", "hp", "wt", "am", "gear")] ui <- fluidPage( fluidRow( column(width = 4, plotOutput("plot1", height = 300, click = "plot1_click", brush = brushOpts( id = "plot1_brush" ) ) ) ), fluidRow( column(width = 6 ), column(width = 6, verbatimTextOutput("brush_info") ) ) ) server <- function(input, output) { output$plot1 <- renderPlot({ ggplot(mtcars2, aes(wt, mpg)) + geom_point() }) # Observe brush events to auto-show modal with selected points observeEvent(input$plot1_brush, { selected_points <- brushedPoints(mtcars2, input$plot1_brush) # Only show modal if there are selected points if(nrow(selected_points) > 0){ showModal(modalDialog( title = "Selected Points", renderPrint(selected_points), easyClose = TRUE )) } }) output$brush_info <- renderPrint({ brushedPoints(mtcars2, input$plot1_brush) }) } shinyApp(ui, server)
Key Changes Explained:
- Removed the "Show points" button: Since we’re triggering the modal automatically, this button is no longer needed.
- Brush-triggered observer: We replaced the button click observer with
observeEvent(input$plot1_brush, ...)—this runs every time the brush selection is updated. - Guard against empty selections: We check if any points were actually selected (
nrow(selected_points) > 0) before showing the modal, so you won’t get empty popups when clearing the brush. - In-modal data display: The selected points are printed directly in the modal using
renderPrint(), keeping the same format as your originalbrush_infooutput.
内容的提问来源于stack exchange,提问作者Henk Straten
相关产品推荐
相关产品推荐

