R 闪亮并巧妙地获得图例点击事件图例、事件、巧妙地

2023-09-06 07:36:48 作者:青春太过潦草う

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

I have an R shiny page, and am filtering the data based on clicking a pie graph. It would be great if I could trigger the same filtering event from clicking legend entries, but I can't seem to find the event trigger, so it just filters that chart without propagating to the other charts. Is a legend click event accessible?

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)

推荐答案

给未来的读者

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

Plotly now has created an event called plotly_relayout. This event is triggered on layout changes. Clicking on the legend is one of these changes.

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

One of the variables in this event is called hiddenlabels. This variable contains all the names of the legend traces that are hidden.

observe({
    relayout <- event_data("plotly_relayout")
    hidden_labels <- relayout$hiddenlabels
    print(hidden_labels)
  })

编辑

检查 如果 plotly_relayout 不适合您,则单击 R Shiny 中 plotly 图表图例中的名称时的事件.

Check event when clicking a name in the legend of a plotly's graph in R Shiny if plotly_relayout is not working for you.

 
精彩推荐
图片推荐