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

如何在ggplotly中实现框选点后展示全部选中数据的表格?

实现ggplotly框选点后展示对应数据表格

原代码仅支持点击单个点展示对应行数据,要实现框选工具选中多个点后展示所有选中行的表格,只需针对事件类型和数据筛选逻辑做两处关键修改:

修改后的完整代码

library(tidyverse)
library(plotly)
library(shiny)

d <-  mtcars %>% 
  rownames_to_column("car")

# UI  ----
ui <- fluidPage(plotlyOutput("plot"),
                tableOutput("selected_table"))

# server  ----
server <- function(input, output) {
  output$plot <- renderPlotly({
    
    key <- d$car
    
    p <- d %>% 
      ggplot(aes(x = disp, y = mpg, color = factor(cyl),
                 key = key)) +
      geom_point(size = 4, alpha = 0.7)
    
    ggplotly(p) %>% 
      event_register("plotly_selected")  # 注册框选事件,替代原点击事件
  })
  
  output$selected_table <- renderTable({
    selected_points <- event_data(event = "plotly_selected", priority = "event")
    req(selected_points)  # 未选中任何点时不渲染表格
    filter(d, car %in% selected_points$key)  # 批量筛选所有选中点对应的行
  })
}

# app ----
shinyApp(ui = ui, server = server)

关键修改说明

  1. 替换事件类型:
    • 将原代码的event_register("plotly_click")改为event_register("plotly_selected"),这是plotly专门用于捕获框选(或套索选)操作的事件。
  2. 调整数据筛选逻辑:
    • 获取框选数据时,event_data("plotly_selected")会返回所有选中点的信息,其中key字段是一个包含所有选中点标识的向量。
    • 筛选数据时用car %in% selected_points$key替代原有的car == point$key,实现批量匹配所有选中的行。
  3. UI组件命名优化:
    • 将原tableOutput("click")改为tableOutput("selected_table"),更贴合功能语义,非必须但提升可读性。

使用时,点击plotly图表工具栏中的框选工具(或套索工具)选中多个点,下方表格会自动更新展示所有选中行的完整数据。

内容的提问来源于stack exchange,提问作者Matti Heino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:10:30