0

I'm aware of https://plot.ly/r/shinyapp-plotly-events/ and have been using it as a guide. But the ggplot element I'm converting to plotly is the output from the fviz_dend function of the factoextra package. Here's a minimum shiny app example I'm working with:

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)

So I'm trying to use the key accessed with event_data("plotly_selected")[5] in order to filter the data table, and while event_data("plotly_selected")[5] does show the key per output$selected_points, it is somehow not passed to the datatable filter.

saheed
  • 340
  • 2
  • 12

1 Answers1

1

It looks like event_data will return a data frame with multiple rows. Instead of filtering with == you will need %in% instead to see which multiple cars are contained within the multiple possible selections from plotly_selected. In addition, even though you subset by column 5, you still have a data frame, and need to include the column key only for filtering (containing a vector of cars). This should work:

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

Or

mtcars[which(rownames(mtcars) %in% event_data("plotly_selected")[["key"]]), ]
Ben
  • 28,684
  • 5
  • 23
  • 45