Reputation: 177
Plotly has the function event_data which will respond to clicks on points of a plot. However, you have to specify a "source" for event_data which identifies the plot you want to watch.
Is there a way to respond to clicks on any plot and get the source id of the given click?
Upvotes: 1
Views: 1020
Reputation: 19544
You can iterate over a source list, but you have to keep track of the changes yourself as only a new click on a given plot overwrites a previous click event:
shinyApp(ui=fluidPage(plotlyOutput("plot1"),
plotlyOutput("plot2")),
server=
function(input, output, session) {
output$plot1 <- renderPlotly(plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length, source="plot1"))
output$plot2 <- renderPlotly(plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length, source="plot2"))
states <- reactiveValues(source = c("plot1", "plot2"), value = c(0,0), changed = c(FALSE,FALSE))
observe({
for(src in states$source){
if( !is.null(event_data("plotly_click", source = src) ) ){
value <- event_data("plotly_click", source = src)[[2]]
if(states$value[states$source==src]!=value ){
states$value[states$source==src] <- value
states$changed[states$source==src] <- TRUE
}
}
}
if(sum(states$changed)>0)
print(paste(states$source[states$changed], 'has changed'))
states$changed <- c(FALSE,FALSE)
})
})
Upvotes: 1