Dea*_*ali 5 r shiny plotly ggplotly
我正在使用plotly::ggplotly()并且我需要用户能够选择单个点并通过刷亮选择多个点。我希望两个选择选项并行存在。用户应该能够点击一个点并套索选择几个点,并且应该记录这两条信息。
我遇到的问题是,如果我点击一个点,那么套索选择会被重置。但相反的情况并非如此:如果我套索选择然后单击一个点,那么两者都会保留。
这是这个问题的 GIF

这是我的代码:
library(shiny)
library(plotly)
ui <- fluidPage(
plotlyOutput("plot"),
verbatimTextOutput("click"),
verbatimTextOutput("brush")
)
server <- function(input, output, session) {
nms <- row.names(mtcars)
output$plot <- renderPlotly({
p <- ggplot(mtcars, aes(x = mpg, y = wt, key = nms)) + geom_point()
ggplotly(p) %>% layout(dragmode = "lasso")
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (!is.null(d)) d
})
output$brush <- renderPrint({
d <- event_data("plotly_selected")
if (!is.null(d)) d
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)
重现:
如果将 传递event_data给函数外部的对象,renderPrint()这应该可以工作。如果删除下面突出显示的可选行,您还可以保留以前的套索/单击结果:
ui <- fluidPage(
plotlyOutput("plot"),
verbatimTextOutput("click"),
verbatimTextOutput("brush")
)
server <- function(input, output, session) {
frame1 <- data.frame()
frame2 <- data.frame()
nms <- row.names(mtcars)
output$plot <- renderPlotly({
p <- ggplot(mtcars, aes(x = mpg, y = wt, key = nms)) + geom_point()
ggplotly(p) %>% layout(dragmode = "lasso")
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (!is.null(d)) {
frame1 <<- frame1[is.null(frame1$pointNumber), ] # Optional line to remove the previous selections
frame1 <<- rbind(frame1, d)
}
frame1
})
output$brush <- renderPrint({
d <- event_data("plotly_selected")
if (!is.null(d)) {
frame2 <<- frame2[is.null(frame2$pointNumber), ] # Optional line to remove the previous selections
frame2 <<- rbind(frame2, d)
}
frame2
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)