R Shiny中的plotly(scattergeo)地图的事件数据

时间:2016-12-13 16:28:36

标签: r maps plotly shiny

我正在构建一个闪亮的应用程序,我在绘制地图事件数据时遇到了一些麻烦。我在过去创建了一个绘图散点图,并在plot_ly函数中定义了一个'key'变量。如果我点击散点图中的某个点,则会提取该密钥,该密钥将用于对数据框进行子集化并生成后续图。我在下面的代码中遵循相同的格式,但密钥没有存储在事件数据中。事件数据仅包含'curveNumber'和'pointNumber'。它似乎适用于这里找到的等值线图:https://plot.ly/r/shinyapp-map-click/但我不能让它为'scattergeo'工作。

非常感谢任何帮助。

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 个答案:

答案 0 :(得分:0)

获取密钥的解决方法是替换:

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

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

看起来key正在使用rownames。