2016-12-13 22 views
0

我正在构建一个有光泽的应用程序,并且在绘制地图事件数据时遇到了一些问题。我在过去创建了一个阴谋散点图,并在plot_ly函数中定义了一个“关键”变量。如果我点击散点图中的某个点,则会提取该关键点,并将该关键点用于子集数据框并生成后续图。我在下面的代码中使用了相同的格式,但密钥没有存储在事件数据中。事件数据只包含'curveNumber'和'pointNumber'。它似乎适用于在这里找到的c​​horopleth地图:https://plot.ly/r/shinyapp-map-click/但我无法让它为'scattergeo'工作。在R中绘制(scattergeo)地图的事件数据Shiny

任何帮助将不胜感激。

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) 

回答

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。

+0

现在我可以在点击某个点时看到事件数据中的关键点。但是,ID 20的事件数据中的键只返回'2'而不是20,而对于ID 35,返回3而不是'35'。这是否也会发生在你身上?我不知道为什么它只会返回第一位。 – SoloAus

+0

这可能与https://github.com/ropensci/plotly/issues/505有关。在你的例子中,当我用id = 40替换id = 35时,键是4。看起来第二个单位被切断了。 – MLavoie