【问题标题】:Event data for plotly (scattergeo) maps in R ShinyR Shiny 中 plotly (scattergeo) 地图的事件数据
【发布时间】:2017-04-28 19:13:44
【问题描述】:

我正在构建一个闪亮的应用程序,但我在使用 plotly 地图事件数据时遇到了一些问题。我过去创建了一个散点图,并在 plot_ly 函数中定义了一个“关键”变量。如果我单击散点图中的一个点,则会提取密钥,并且该密钥将用于对数据框进行子集化并生成后续图。我在下面的代码中遵循相同的格式,但密钥没有存储在事件数据中。事件数据仅包含“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)

【问题讨论】:

    标签: r maps plotly shiny


    【解决方案1】:

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

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

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

    看起来key 正在处理行名。

    【讨论】:

    • 现在我可以在点击一个点时看到事件数据中的键。但是,id 20 的事件数据中的键仅返回“2”而不是 20,而对于 id 35,它返回 3 而不是“35”。你也有这种情况吗?我不知道为什么它只会返回第一个数字。
    • 这可能与github.com/ropensci/plotly/issues/505 有关。在您的示例中,当我将 id=35 替换为 id=40 时,键为 4。看起来第二个单元被切断了。
    猜你喜欢
    • 2018-10-21
    • 2022-10-18
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多