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

如何在Shiny中点击表格行时高亮绘图上的对应点位?

实现Shiny表格行点击高亮地图点位

需求说明

现有一个包含北卡罗莱纳州地图和点位表格的Shiny应用,需要实现点击表格中的行时,对应地图上的点位自动高亮的交互效果。

修改后的完整代码

library(shiny)
library(sf)
library(purrr)
library(tidyverse)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

(lon <- 0:9 - 84)
(lat <- 0:2 + 34)

((
  expand_grid(lon, lat)
  |> mutate(name = c(letters, LETTERS[1:4]))
  |> mutate(point = map2(lon, lat, ~ st_point(c(.x, .y))))
  |> mutate(feature = st_sfc(point, crs = 4326))  # 修正为标准WGS84坐标系
  |> select(name, feature)
) -> raw)

dots <- st_sf(raw[, "name"], geometry = st_sfc(raw$feature))

ui <- fluidPage(
  fluidRow(
    column(2,  tableOutput("table") ),
    column(10,  plotOutput("map") )
  )
)

server <- function(input, output, session) {
  
  # 输出表格:移除sf对象的几何列,解决原代码报错问题
  output$table <- renderTable(
    st_drop_geometry(dots)
  )
  
  # 反应式获取选中行对应的点位
  selected_dots <- reactive({
    req(input$table_rows_selected)
    dots[input$table_rows_selected, ]
  })
  
  output$map <- renderPlot({
    ggplot() +
      geom_sf(data = nc, fill = "lightgray") +
      # 绘制未选中的基础点位
      geom_sf(data = dots, color = "darkblue", size = 2) +
      # 绘制选中的高亮点位,用醒目样式区分
      geom_sf(data = selected_dots(), color = "red", size = 4, shape = 19)
  })
}

shinyApp(ui, server, options = list(
  launch.browser = TRUE
))

关键改动说明

  • 表格数据修复:用st_drop_geometry(dots)移除sf对象的几何列,解决原代码中直接使用dots渲染表格报错的问题,确保表格正常显示。
  • 交互逻辑实现:利用Shiny内置的input$table_rows_selected获取用户点击的表格行号,通过反应式变量selected_dots筛选出对应点位数据。
  • 高亮样式区分:绘图时分别渲染未选中和选中的点位,选中点位使用更大尺寸、红色填充,与未选中的深蓝色点位形成明显视觉差异,实现高亮效果。
  • 坐标系修正:将原代码中的CRS编号从4236改为4326(WGS84标准坐标系),避免坐标系不匹配的潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:32:15