getting correct click coords with ggplot map in shiny

 ̄綄美尐妖づ 提交于 2019-12-22 10:10:06

问题


I have the start of a shiny app with a ggplot map of the world. I would like to get the coordinates of the click on the plot so users can do things with the map, but the coordinates are very strange (either NULL or something very small). Clicking repeatedly only seems to change one coordinate:

ui.R:

library(shiny)

# Define UI for application
shinyUI(pageWithSidebar(

  # Application title
  headerPanel("My App"),
  sidebarPanel(
    textOutput("clickcoord")
  ),

  # Show a plot of the generated distribution
  mainPanel(
    plotOutput("myworld", height="600px", clickId="plotclick")
  )
))

server.R:

library(shiny)
library(maps)
library(mapdata)
library(ggplot2)
library(rworldmap)

shinyServer(function(input, output) {

  output$myworld <- renderPlot({

     world <- map_data("world")
     worldmap <- ggplot(aes(x = long, y = lat, group = group), data = world) +
       geom_path()

    print(worldmap)
  })

  output$clickcoord <- renderPrint({
          print(input$plotclick)
  })
})

If I just use the map() command to generate a non-ggplot world map, I get what looks like good lat/long values for the click coords:

server.R (modified):

library(shiny)
library(maps)
library(mapdata)

shinyServer(function(input, output) {

    output$myworld <- renderPlot({
      map("world2Hires")
    })

    output$clickcoord <- renderPrint({
      print(input$plotclick) 
    })

})

回答1:


Simply replace print(worldmap) with worldmap in your original code you will get what you want. Shiny works perfectly fine with ggplot2. The function print() seems generate a figure whose x and y are reset in the range (0, 1).



来源:https://stackoverflow.com/questions/21655830/getting-correct-click-coords-with-ggplot-map-in-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!