我知道https://plot.ly/r/shinyapp-plotly-events/,并一直将其用作指南。但是我要转换为plotly的ggplot元素是fviz_dend
包的factoextra
函数的输出。这是我正在使用的最小的闪亮应用程序示例:
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)
因此,我尝试使用通过key
访问的event_data("plotly_selected")[5]
来过滤数据表,尽管event_data("plotly_selected")[5]
确实显示了每个output$selected_points
的密钥,不知何故没有传递到数据表过滤器。
答案 0 :(得分:1)
看来event_data
将返回一个包含多行的数据帧。除了使用==
进行过滤之外,您还需要使用%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"]]), ]