Here is a working example of extracting the on-click event. I would like to ask you if there is a way to update the clicked point with either increase in size or highlight it etc.,?
library(shiny)
library(plotly)
ui <- fluidPage(
plotlyOutput("plot"),
verbatimTextOutput("click")
)
server <- function(input, output, session) {
nms <- row.names(mtcars)
output$plot <- renderPlotly({
p <- ggplot(mtcars, aes(x = mpg, y = wt, col = as.factor(cyl), key = nms)) +
geom_point()
ggplotly(p)
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (is.null(d)) "Click events appear here (double-click to clear)"
else cat("Selected point associated with Car: ", d$key)
})
}
shinyApp(ui, server)
I have searched SO and other appropriate sources for finding a solution to the below question, but could not find one.
Update:
- This solution works better for this toy plot. But, my original use case contains 50+ levels for the variable of interest and there are high chances that Magenta or any other color would already be present. Also, it takes a considerable amount of time to change the color.
- Is there any way to increase the size of the clicked point to differentiate it from 100s of nearby points?
A related question to change the shape of the clicked point has been asked here.
You could add
Plotly
's events to your Shiny app withhtmlwidget
'sonrender
function.An array of
colors
is passed to therestyle
function. The selected point (pointNumber
) is colored magenta while the others get the color from the legend. You could do the same thing with themarker
size, marker symbol is a bit more tricky becausePlotly
does not accept arrays here.Some explanations:
plotly_click
pass some information (data
in this case) in the event functiondata.points
contains the points for which the event was triggereddata.points[0]
wherepointNumber
is the index of the original array andcurveNumber
is the trace number.div
where the plot is drawndocument.getElementsByClassName('plotly')[0].data
document.getElementsByClassName('legendpoints')[i]
wherei
is the index of the legendonrender
in this case