r-按情节单击事件识别子批次



问题:假设一个plotly子地块将多个地块组合在一起。除了curveNumber和pointNumber之外,还有没有办法通过plotly_click事件来识别子地块编号?例如(例如下面的代码(,p1被分配数字0,p2被分配数字1,p3被分配数字2,我可以使用类似于plotly_click事件的命令来获得这些数字?

所需输出:

curveNumber pointNumber   x  y plotNumber
4           1 Top 15         2

代码示例

library(shiny)
library(plotly)
library(data.table)
dt <- data.table(
quarter = c("2020 Q1", "2020 Q1", "2019 Q4", "2019 Q4", "2019 Q3", "2019 Q3"),
type = c("Hop", "Top", "Hop", "Top", "Hop", "Top"),
count2 = c(3, 4, 5, 6, 0, 1),
count = c(10, 20, 30, 40, 0, 15)
)
dt[, type := as.factor(type)]
ui <- fluidPage(
mainPanel(
plotlyOutput("plot")
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$plot <- renderPlotly({
p1 <- plot_ly(dt[quarter == "2020 Q1"],
x = ~type,
y = ~count,
source = "plot_y") %>%
add_bars(y = ~count) %>%
add_bars(y = ~count2) %>%
layout(barmode = "stack")
p2 <- plot_ly(dt[quarter == "2019 Q4"],
x = ~type,
# y = ~count,
source = "plot_y")%>%
add_bars(y = ~count) %>%
add_bars(y = ~count2)%>%
layout(barmode = "stack")
p3 <- plot_ly(dt[quarter == "2019 Q3"],
x = ~type,
y = ~count,
source = "plot_y")%>%
add_bars(y = ~count) %>%
add_bars(y = ~count2)%>%
layout(barmode = "stack")
list_p <- list(p1, p2, p3)
subplot(list_p, shareY = TRUE)
})
observe({
click <- event_data("plotly_click", source = "plot_y")
req(click)
print(click)
})
}
# Run the application
shinyApp(ui = ui, server = server)

我不认为可以向event_data添加类似plotNumber的内容,但可以使用customdatakey属性向event_data传递额外信息。

以下是使用customdata:更新的服务器功能

# Define server logic required to draw a histogram
server <- function(input, output) {
output$plot <- renderPlotly({
p1 <- plot_ly(dt[quarter == "2020 Q1"],
x = ~type,
y = ~count,
customdata='p1',
source = "plot_y") %>%
add_bars(y = ~count) %>%
add_bars(y = ~count2) %>%
layout(barmode = "stack")
p2 <- plot_ly(dt[quarter == "2019 Q4"],
x = ~type,
customdata='p2',
# y = ~count,
source = "plot_y")%>%
add_bars(y = ~count) %>%
add_bars(y = ~count2)%>%
layout(barmode = "stack")
p3 <- plot_ly(dt[quarter == "2019 Q3"],
x = ~type,
y = ~count,
customdata='p3',
source = "plot_y")%>%
add_bars(y = ~count) %>%
add_bars(y = ~count2)%>%
layout(barmode = "stack")
list_p <- list(p1, p2, p3)
subplot(list_p, shareY = TRUE)
})
observe({
click <- event_data("plotly_click", source = "plot_y")
req(click)
print(click)
})
}

输出:

curveNumber pointNumber   x  y customdata
1           4           1 Top 15         p3

最新更新