问题描述
我正在尝试做一些看似简单的事情:当用户单击数据点或使用套索选择选择多个点时,我想用不同的颜色绘制这些点.为此,我查看选择了哪些点,并将 col
变量添加到数据框,然后告诉 ggplot 根据该列为点着色.
I'm trying to do something seemingly simple: when the user clicks on a data point or select multiple points with lasso selection, I want to draw these points in a different colour. In order to do that, I look at what points are selected, and add a col
variable to the dataframe, and I tell the ggplot to colour the points according to that column.
它确实适用于第一个选择.但是,只要已经选择了点,选择下一组点就不起作用.我添加了调试语句以查看从 plotly 返回的数据,并且在初始选择后似乎返回不同的 pointNumber
和 curveNumber
.我找不到任何关于这些变量如何工作的文档,而且我不确定如何解决这个问题.
It does work for the first selection. But whenever there are already selected points, selecting the next set of points doesn't work. I've added debug statements to see what data is returned from plotly, and it seems like it returns different pointNumber
and curveNumber
after the initial selection. I couldn't find any documentation about how these variables work and I'm not sure how to fix this issue.
这是一个显示问题的 GIF
这里是重现的代码:
library(plotly)
library(shiny)
ui <- fluidPage(
plotlyOutput("plot")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
click_data <- event_data("plotly_click", source = "select")
select_data <- event_data("plotly_selected", source = "select")
data <- mtcars
data$col <- "black"
if (!is.null(select_data)) {
cat(str(select_data))
idx <- select_data$pointNumber + 1
data[idx, "col"] <- "blue"
}
if (!is.null(click_data)) {
cat(str(click_data))
idx <- click_data$pointNumber + 1
data[idx, "col"] <- "red"
}
p <- ggplot(data, aes(mpg, wt, col = I(col))) + geom_point()
ggplotly(p, source = "select")
})
}
shinyApp(ui, server)
我还被告知,也许我需要做的是创建自己的行标识符并将其传递给 key
美学.我不确定这意味着什么我尝试定义 key <- row.names(data)
然后将 key=key
传递给 ggplot 的 aes(),但这并没有似乎没有任何改变.
I've also been told that perhaps what I need to do is create my own row identifier and pass it to the key
aesthetic. I'm not sure what that means I tried defining key <- row.names(data)
and then passing key=key
to ggplot's aes(), but that didn't seem to change anything.
推荐答案
Carson Sievert 回答了我的问题 一个要点
Carson Sievert answered my question on a gist
答案如下:
我知道这似乎违反直觉,但 pointNumber 不是可靠的行标识符.使用这样的关键变量:
I know it seems counter-intuitive, but pointNumber isn't a reliable row identifier. Use a key variable like this:
library(plotly)
library(shiny)
mtcars$key <- row.names(mtcars)
mtcars$col <- "black"
ui <- fluidPage(
plotlyOutput("plot")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
click_data <- event_data("plotly_click")
select_data <- event_data("plotly_selected")
if (!is.null(select_data)) {
mtcars[mtcars$key %in% select_data$key, "col"] <- "blue"
}
if (!is.null(click_data)) {
mtcars[mtcars$key %in% click_data$key, "col"] <- "red"
}
p <- ggplot(mtcars, aes(mpg, wt, col = I(col), key = key)) +
geom_point()
ggplotly(p) %>% layout(dragmode = "lasso")
})
}
shinyApp(ui, server)
这篇关于即使在修改数据后如何使用 plotly 为所选点返回相同的 event_data 信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!