在绘图中,如何保留有关套索选择和单击点的信息? [英] In plotly, how do I retain the information about both the lasso selection and the clicked point?
问题描述
我正在使用plotly::ggplotly()
,我需要用户既可以选择单个点又可以通过刷涂选择多个点.我希望两个选择选项并行存在.用户应该能够单击一个点并套索选择多个点,并且应该记录这两条信息.
I'm using plotly::ggplotly()
and I need the user to be able to both select a single point and to select multiple points with brushing. I want both selection options to exist in parallel. The user should be able to click on a point and to lasso select several points, and both of those pieces of information should be recorded.
我遇到的问题是,如果单击某个点,则会重设套索选择.但是事实并非如此:如果我套索选择然后单击一个点,则两者都会保留.
The problem I'm having is that if I click on a point, then the lasso selection gets reset. But the opposite is not true: if I lasso select and then click on a point, then both are retained.
这是此问题的GIF文件
Here's a GIF of this issue
这是我的代码:
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)
要重现:
- 单击单个点
- 进行套索选择
- 当前都可见
- 单击其他点
- 现在套索选择信息不见了
- 再次选择套索,两个都再次可见
推荐答案
如果将event_data
传递给renderPrint()
函数外部的对象,则此方法应该起作用.如果您删除下面突出显示的可选行,您还可以保留以前的套索/点击结果:
If you pass the event_data
to an object outside the renderPrint()
function this should work. You can also keep previous lasso/click results if you remove the optional lines highlighted below:
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)
这篇关于在绘图中,如何保留有关套索选择和单击点的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!