1
votes

I'm building a shiny app and I'm having some trouble with the plotly map event data. I have created a plotly scatterplot in the past and defined a 'key' variable within the plot_ly function. If I clicked on a point in the scatterplot, the key would be extracted and the key would be used to subset a dataframe and produce a subsequent plot. I'm following the same format in the code below, but the key isn't being stored in the event data. The event data only contains the 'curveNumber' and the 'pointNumber'. It seems to work for the choropleth map found here: https://plot.ly/r/shinyapp-map-click/ but I can't get it to work for 'scattergeo'.

Any help would be greatly appreciated.

library(shiny)
library(plotly)

ui <- shinyUI(fluidPage(

  titlePanel("My Shiny App"),
  sidebarLayout(
    sidebarPanel(
      numericInput("idnum", label = h3("ID #"), 
                   value = 3)
    ),
    mainPanel(
      plotlyOutput("map"),
      verbatimTextOutput("click")
    )
  )
))

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

  output$map <- renderPlotly({

    df <- data.frame(id = c(3,6,20,35), lat = c(30.67,32.46,37.83,29.62), lon = c(-97.82, -62.34, -75.67, -85.62))

    sub <- df[which(df$id == input$idnum),]

    g <- list(
      scope = 'north america',
      showland = TRUE,
      landcolor = toRGB("grey83"),
      subunitcolor = toRGB("white"),
      countrycolor = toRGB("white"),
      showlakes = TRUE,
      lakecolor = toRGB("white"),
      showsubunits = TRUE,
      showcountries = TRUE,
      resolution = 50,
      projection = list(
        type = "miller",
        rotation = list(lon = -100)
      ),
      lonaxis = list(
        showgrid = TRUE,
        gridwidth = 0.5,
        range = c(-140, -55),
        dtick = 5
      ),
      lataxis = list(
        showgrid = TRUE,
        gridwidth = 0.5,
        range = c(20, 60),
        dtick = 5
      )
    )

    plot_ly(sub, lon = ~lon, lat = ~lat, key = ~id, text = ~paste(id), hoverinfo = "text",
            marker = list(size = 10),
            type = 'scattergeo',
            locationmode = 'USA-states') %>%
      layout(title = 'Locations', geo = g)
  })

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

shinyApp(ui = ui, server = server)
1

1 Answers

0
votes

A workaround to get your key is to replace:

sub <- df[which(df$id == input$idnum),]

with

sub <- df[which(df$id == input$idnum),] 
rownames(sub) <- sub$id 
key <- row.names(sub)

it looks like key is working with rownames.