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

Shiny应用中ggplot2生成的空间地图显示异常该如何解决

问题描述

我开发了一款支撑水文建模教学的应用,学生可在其中选择要操作的测站。为了丰富学生可获取的信息,我对应用做了升级,新增在国家底图上展示测站及对应集水区的功能,同时搭配更详细的局部地图。
以下是可复现问题的简化代码:

station_data <- read.csv("station_timeseries.csv",na.strings = "NaN",fileEncoding="UTF-8-BOM")
station_data$date <- as.Date(station_data$date,"%d/%m/%Y")

station_lat <- read.csv("station_coord.csv",fileEncoding="UTF-8-BOM")

GB_boundary <- st_read("./maps/GB_boundary.shp")
catchment_boundary <- st_read("./maps/Catchments.shp")

ui <- shinyUI(fluidPage(
  sidebarPanel(
    # Select station
    selectInput(inputId = "station", label = strong("Select station"),
                choices = unique(station_data$gauge_name))
    ),
  tabPanel("Catchment characteristics",plotOutput(outputId = "Map"))
)
)

server <- shinyServer(function(input, output) {
  ## Catchment and station map ----
  output$Map <- renderPlot({
    station <- station_lat[station_lat$gauge_name==input$Station,]$gauge_id
    bbox <- st_bbox(catchment_boundary[catchment_boundary$ID==station,])
    large_map <- ggplot()+
      geom_sf(data=GB_boundary,size=1,color="black",fill="cyan1")+
      geom_sf(data=catchment_boundary[catchment_boundary$ID==station,],size=1,color="black",fill="red")+
      theme_bw()
    detail_map <- ggplot()+
      geom_sf(data=GB_boundary,size=1,color="black",fill="cyan1")+
      geom_sf(data=catchment_boundary[catchment_boundary$ID==station,],size=1,color="black",fill="red")+
      coord_sf(xlim=c(bbox[1]-20000,bbox[3]+20000),ylim = c(bbox[2]-20000,bbox[4]+20000),expand = FALSE)+
      ggtitle("Catchment and station location")+
      theme_bw()
    grid.arrange(large_map,
                 detail_map,
                 ncol = 2,
                 widths = c(2,5))
  })
})

shinyApp(ui = ui, server = server)

上述ggplot2代码单独运行可生成目标布局的双图,但运行Shiny应用时仅能显示国家底图,没有加载选中测站对应的集水区图层,也没有生成右侧的局部放大图。


解决方案

问题核心是Shiny输入ID的大小写不匹配,按以下操作修正即可:

  • 修正服务端的输入引用名:将input$Station改为input$station,和UI中定义的inputId完全一致,就能正常获取选中的测站名称,后续的集水区筛选、边界框计算逻辑都可以正常运行。
  • 可选补充空值校验,避免初始化未选择测站时的报错:在绘图逻辑开头新增req(input$station)语句,等待用户完成测站选择后再执行绘图代码。

修正后即可正常渲染左侧全局小地图+右侧局部放大图的预期效果,两个图层都可以正常加载。

内容的提问来源于stack exchange,提问作者David Haro Monteagudo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:06:08