R 闪亮且有情节地获取图例点击事件

Mat*_*att 3 r shiny plotly

我有一个 R 闪亮页面,正在根据单击饼图过滤数据。如果我可以通过单击图例条目触发相同的过滤事件,那就太好了,但我似乎找不到事件触发器,因此它只是过滤该图表而不传播到其他图表。图例点击事件是否可以访问?

library(data.table)
library(plotly)
library(shiny)

dt = as.data.table(mtcars)


ui <- fluidPage(
  plotlyOutput("pie1"),
  plotlyOutput("pie2")
)


server <- function(input, output){

  gearDT = reactive({
    return(dt[,.N,by=gear])
  })

  cylDT = reactive({
    return(dt[,.N,by=cyl])
  })

  output$pie1 <- renderPlotly({

    plot_ly(gearDT(), labels = ~gear, values = ~N, type = "pie") %>%
      layout(showlegend = TRUE)


  })

  output$pie2 <- renderPlotly({

    plot_ly(cylDT(), labels = ~cyl, values = ~N, type = "pie")  %>%
      layout(showlegend = TRUE)


  })
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

Wil*_*ren 5

对于未来的读者

Plotly 现在创建了一个名为plotly_relayout. 此事件在布局更改时触发。单击图例是这些更改之一。

此事件中的变量之一称为hiddenlabels。此变量包含隐藏的图例轨迹的所有名称。

observe({
    relayout <- event_data("plotly_relayout")
    hidden_labels <- relayout$hiddenlabels
    print(hidden_labels)
  })
Run Code Online (Sandbox Code Playgroud)

编辑

如果不适合您,请在 R Shiny 中单击绘图图例中的名称时检查事件plotly_relayout