问题
I want to set up an interactive graph with shiny and plotly. Shiny has a build in feature to get info about the user interaction. Like: input$plot_click, input$plot_dblclick, input$plot_hover and input$plot_brush. See: http://shiny.rstudio.com/articles/plot-interaction.html
Is there any option to get this over the Plotly API? Or can the API just handle one direction?
Plotly is really cool. Would love to use it in my shiny apps.
Thanks and best regards
Nico
回答1:
Yes, there are click and hover bindings to Plotly graphs through the postMessage API: https://github.com/plotly/postMessage-API
A sketch of how to use the postMessage API with Shiny is here: http://moderndata.plot.ly/dashboards-in-r-with-shiny-plotly/
And the code is here: https://github.com/chriddyp/plotly-shiny
回答2:
There is now an event_data function from the plotly package itself that handles hovers, clicks, brushing etc.
There is a Shiny demo in the package that describes the usage:
library(plotly)
shiny::runApp(system.file("examples", "plotlyEvents", package = "plotly"))
app.R
library(shiny)
library(plotly)
ui <- fluidPage(
radioButtons("plotType", "Plot Type:", choices = c("ggplotly", "plotly")),
plotlyOutput("plot"),
verbatimTextOutput("hover"),
verbatimTextOutput("click"),
verbatimTextOutput("brush"),
verbatimTextOutput("zoom")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
# use the key aesthetic/argument to help uniquely identify selected observations
key <- row.names(mtcars)
if (identical(input$plotType, "ggplotly")) {
p <- ggplot(mtcars, aes(x = mpg, y = wt, colour = factor(vs), key = key)) +
geom_point()
ggplotly(p) %>% layout(dragmode = "select")
} else {
plot_ly(mtcars, x = mpg, y = wt, key = key, mode = "markers") %>%
layout(dragmode = "select")
}
})
output$hover <- renderPrint({
d <- event_data("plotly_hover")
if (is.null(d)) "Hover events appear here (unhover to clear)" else d
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (is.null(d)) "Click events appear here (double-click to clear)" else d
})
output$brush <- renderPrint({
d <- event_data("plotly_selected")
if (is.null(d)) "Click and drag events (i.e., select/lasso) appear here (double-click to clear)" else d
})
output$zoom <- renderPrint({
d <- event_data("plotly_relayout")
if (is.null(d)) "Relayout (i.e., zoom) events appear here" else d
})
}
shinyApp(ui, server, options = list(display.mode = "showcase"))
They also have examples of linked brushing and clicks on their main GitHub page:
https://github.com/ropensci/plotly
来源:https://stackoverflow.com/questions/31592682/can-i-get-back-info-like-hover-location-brush-location-or-click-location