You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny使用stamen地图时出现object 'map' not found报错问题

错误原因
  • renderPlot() 要求多行绘图逻辑必须包裹在大括号 {} 内,你当前代码用逗号分隔多行语句,map <- get_stamenmap(...) 被识别为renderPlot()的第一个参数,后续ggmap(map)相关代码被识别为无关的额外参数,不在同一个执行作用域内,自然无法找到map变量。
  • ggplot语法存在括号闭合错误:stat_density_2d()的括号提前闭合,导致aes()、geom参数被放在图层函数外部,语法逻辑不成立。
修正后的完整代码
library(shiny)
library(ggmap)
# 加载ggmap内置的crime数据集
data(crime)
# 调用stamen地图前需先注册Stadia Maps密钥,替换下方引号内内容为你申请的密钥
# register_stadiamaps("your_api_key")

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel("Options",
                 radioButtons(inputId = "radio",
                              label = "Type of Offense",
                              choices = list("Murder" = 'murder',
                                             "Robbery" = 'robbery',
                                             "Assault" = 'aggravated assault',
                                             "Burglary" = 'burglary',
                                             "Auto-Theft" = 'auto theft',
                                             "Theft" = 'theft',
                                             "Rape" = 'rape'),
                              selected = 'murder'),
    ),
    mainPanel(
      plotOutput('plot')
    ),
  )
)
server <- function(input, output){
  output$plot <- renderPlot({
    map <- get_stamenmap(bbox = c(left=-95.8, bottom=29.4, right=-95.0, top=30.0), 
                         zoom = 10, source = "stamen", maptype = "terrain")
    ggmap(map) + 
      stat_density_2d(data = subset(crime, offense == input$radio),
                      aes(x = lon, y = lat, fill = ..level.., alpha = ..level..), 
                      geom = 'polygon') +
      ggtitle("Crimes in Houston, TX")
  })
}

shinyApp(ui, server)
额外说明

原UI代码中冗余的mainPanel("Siebar")已删除,符合Shiny的布局规范。

内容的提问来源于stack exchange,提问作者Rajiv Manuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:15:04