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
相关产品推荐
相关产品推荐

