You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 original brush_info output.

内容的提问来源于stack exchange,提问作者Henk Straten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:39:58