如何从 ggplotly 图表中获取选定的事件数据?

How to grab selected event data from a ggplotly chart?

我知道 https://plot.ly/r/shinyapp-plotly-events/ 并一直将其用作指南。但是我要转换为 plotly 的 ggplot 元素是 factoextra 包的 fviz_dend 函数的输出。这是我正在使用的最小闪亮应用程序示例:

library(factoextra)
library(plotly)
library(shiny)
library(DT)

ui <- fluidPage(
    plotlyOutput("ggp"),
    verbatimTextOutput("selected_points"),
    DT::dataTableOutput("filtered_table")
)
server <- function(input, output, session) {

    ## ggplot output
    fviz <- fviz_dend(
        x                 = hclust(dist(mtcars)),
        k                 = 5,
        show_labels       = TRUE,
        type              = "phylogenic",
        phylo_layout      = "layout_as_tree",
        color_labels_by_k = TRUE,
        palette           = "igv"
    )

    ## convert to ggplotly
    ggfviz <- ggplotly(fviz)

    ## add keys
    for (i in seq(7, 11)) {
        ggfviz[["x"]][["data"]][[i-5]][["key"]] <-
            as.character(ggfviz[["x"]][["data"]][[i]][["text"]])
    }

    output$ggp <- renderPlotly({
        ggfviz
    })

    output$selected_points <- renderPrint({
        event_data("plotly_selected")[5]
    })

    output$filtered_table <- DT::renderDataTable(
        mtcars[which(rownames(mtcars) == event_data("plotly_selected")[5]), ],
    )
}
shinyApp(ui, server)

所以我尝试使用通过 event_data("plotly_selected")[5] 访问的 key 来过滤数据 table,而 event_data("plotly_selected")[5] 确实显示每个 output$selected_points,它以某种方式没有传递给数据table 过滤器。

看起来 event_data 将 return 一个包含多行的数据框。您无需使用 == 进行过滤,而是需要 %in% 来查看 plotly_selected 的多个可能选项中包含哪些多辆汽车。此外,即使您按第 5 列进行子集化,您仍然有一个数据框,并且只需要包含 key 列用于过滤(包含汽车矢量)。这应该有效:

mtcars[which(rownames(mtcars) %in% event_data("plotly_selected")$key), ]

或者

mtcars[which(rownames(mtcars) %in% event_data("plotly_selected")[["key"]]), ]