问题
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