Plotly双击事件无响应问题(Shiny应用场景)
Shiny中Plotly饼图双击事件失效的修复方案
你的代码里双击事件无法触发主要有两个问题:
plot_ly里的ids = ~id属于无效配置,因为数据集filtered_data1()里并没有id列,这会干扰事件数据的正常传递- 没有显式注册
plotly_doubleclick事件,导致Shiny无法捕获双击动作
以下是修正后的完整代码:
library(shiny) library(plotly) ui <- function(){ fluidPage( plotlyOutput("plot2") ) } server <- function(input, output, session){ myPlotEventData2 <- reactive({ event_data(event = "plotly_doubleclick", source = "myPlotSource2") }) myPlotEventData3 <- reactive({ event_data(event = "plotly_click", source = "myPlotSource2") }) filtered_data1 <- reactive({ generation_types <- c("Solar", "Wind", "Hydro", "Nuclear") MWh <- c(150, 200, 180, 250) data.frame(generation_type = generation_types, MWh = MWh) }) output$plot2 <- renderPlotly({ a <- filtered_data1() plot_ly(data = a, labels = ~generation_type, values = ~round(MWh), type = "pie", sort = FALSE, source = "myPlotSource2") %>% event_register("plotly_doubleclick") %>% # 显式注册双击事件 layout(showlegend = FALSE, margin = list(l = 0, r = 0, t = 0, b = 0)) }) observe({ clicked_data <- myPlotEventData2() if (!is.null(clicked_data)) { clicked_segment <- clicked_data$pointNumber + 1 segment_label <- filtered_data1()$generation_type[clicked_segment] segment_value <- filtered_data1()$MWh[clicked_segment] print(paste("双击的板块:", segment_label)) print(paste("板块数值:", segment_value)) } }) observe({ clicked_data <- myPlotEventData3() if (!is.null(clicked_data)) { clicked_segment <- clicked_data$pointNumber + 1 segment_label <- filtered_data1()$generation_type[clicked_segment] segment_value <- filtered_data1()$MWh[clicked_segment] print(paste("单击的板块:", segment_label)) print(paste("板块数值:", segment_value)) } }) } shinyApp(ui, server)
修正说明
- 移除了无效的
ids = ~id参数,避免干扰事件数据解析 - 在
plot_ly管道中添加event_register("plotly_doubleclick"),显式告诉Plotly要监听双击事件 - 调整了打印文本的表述,让日志更清晰
运行修正后的代码后,单击饼图板块会打印单击日志,双击则会打印双击日志,两种交互都能正常触发。
内容的提问来源于stack exchange,提问作者kwame
相关产品推荐
相关产品推荐

