Prradep
Prradep

Reputation: 5716

Mapping the event data information to the plotting information in Shiny reactive plots

How to retrieve the original data used for plotting from the even_data information?

library(plotly)
library(shiny)

ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("click")
)

server <- function(input, output, session) {

  output$plot <- renderPlotly({
    key <- row.names(mtcars)
    p <- ggplot(mtcars, aes(x = mpg, y = wt, colour = factor(vs), key = key)) + 
        geom_point()
    ggplotly(p) %>% layout(dragmode = "select")

  })


  output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (is.null(d)) "Click events appear here (double-click to clear)" else d
  })


}

shinyApp(ui, server)

When clicked on a point, the example output would be similar to

  curveNumber pointNumber    x    y       key
1           1           3 24.4 3.19 Merc 240D

Is there any way possible to map these information to the original dataset mtcars? How would the information in curveNumber, pointNumber will be useful and what do these fields mean?

Upvotes: 1

Views: 1257

Answers (1)

Patrik_P
Patrik_P

Reputation: 3200

The curveNumber is the colour = factor(vs) variable, the pointNumberis the row number +1 within the group (0 or 1 of vs).

So using these two you can do the following:

library(plotly)
library(shiny)
library(dplyr)
ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("click")
)
server <- function(input, output, session) {
  output$plot <- renderPlotly({
    key <- row.names(mtcars)
    p <- ggplot(mtcars, aes(x = mpg, y = wt, colour = factor(vs), key = key)) + 
      geom_point()
    ggplotly(p) %>% layout(dragmode = "select")
  })
  output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (is.null(d)) "Click events appear here (double-click to clear)" else mtcars %>% tibble::rownames_to_column() %>% filter(vs==d$curveNumber) %>% filter(row_number()==d$pointNumber+1)

  })
}
shinyApp(ui, server)

Or, second option, you need to extract the keyfrom event_data and subset mtcars like this:

output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (is.null(d)) "Click events appear here (double-click to clear)" 
    else mtcars[rownames(mtcars) == d$key,]
  })

The complete app:

library(plotly)
library(shiny)
ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("click")
)
server <- function(input, output, session) {
  output$plot <- renderPlotly({
    key <- row.names(mtcars)
    p <- ggplot(mtcars, aes(x = mpg, y = wt, colour = factor(vs), key = key)) + 
      geom_point()
    ggplotly(p) %>% layout(dragmode = "select")
  })
  output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (is.null(d)) "Click events appear here (double-click to clear)" else mtcars[rownames(mtcars) == d$key,]
  })
}
shinyApp(ui, server)

Upvotes: 1

Related Questions