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

Shiny中两个plotly图表借助crosstalk实现跨图选点联动异常问题

修正后可直接运行的完整代码

library(shiny)
library(plotly)
library(crosstalk)

ui <- fluidPage(
  sliderInput("rows", label = "# Rows", min = 50, max = 150, value = 100),
  plotlyOutput("scatter1"),
  plotlyOutput("scatter2")
)

server <- function(input, output, session) {
  
  # 响应式生成共享数据,固定key和group参数
  sd <- reactive({
    df <- iris[1:as.numeric(input$rows),]
    # 行名作为唯一key,固定group保证联动组不随数据更新变更
    SharedData$new(df, key = ~row.names(df), group = "iris_shared_group")
  })
  
  output$scatter1 <- renderPlotly({
    plot_ly(
      sd(),
      x = ~Sepal.Length, 
      y = ~Sepal.Width,
      color = ~Species,
      type = "scatter",
      mode = "markers"
    ) %>% 
      # 开启框选模式,按住Shift可叠加多选
      layout(dragmode = "select") %>%
      event_register("plotly_selected")
  })
  
  output$scatter2 <- renderPlotly({
    plot_ly(
      sd(),
      x = ~Petal.Length, 
      y = ~Petal.Width,
      color = ~Species,
      type = "scatter",
      mode = "markers"
    ) %>% 
      layout(dragmode = "select") %>%
      event_register("plotly_selected")
  })
}

shinyApp(ui, server)

关键修改说明

  • 显式加载crosstalk包,避免底层联动逻辑调用异常
  • 创建SharedData时指定两个核心参数:
    • key:每行数据的唯一标识符,避免crosstalk无法匹配两个图表的对应数据点
    • group:固定的共享组名称,保证响应式数据更新后,两个图表仍属于同一个联动组
  • 给plotly图表设置dragmode = "select"开启框选能力,点击画布空白处即可取消所有选中,按住Shift可叠加选择多个区域
  • 注册plotly_selected事件,保证选择状态可以同步到共享组内的所有组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:36:02