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

如何在R中使用tmap包关联数值与字符串标签并绘制社区地图

实现步骤

首先对空间数据做预处理,生成编号字段与质心坐标:

library(tmap)
library(sf)
library(dplyr)

# 1. 为社区数据添加唯一编号,按社区名称排序生成1-29的ID,可自行调整排序规则
Neighborhood_MN <- Neighborhood_MN %>%
  arrange(ntaname) %>%
  mutate(neigh_id = as.factor(row_number())) # 转因子避免tmap识别为连续数值

# 2. 计算每个社区多边形的质心,用于放置编号标签
neigh_centroids <- st_centroid(Neighborhood_MN)

# 3. 生成图例标签,格式为「编号 - 社区名称」
legend_labels <- paste0(Neighborhood_MN$neigh_id, " - ", Neighborhood_MN$ntaname)

# 你原有调色板仅12种颜色,用colorRampPalette扩展为29种适配所有社区,也可直接替换为其他分类调色板
base_colors <- c("#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462" ,"#b3de69", "#fccde5", "#d9d9d9", "#bc80bd", "#ccebc5" ,"#ffed6f")
extended_colors <- colorRampPalette(base_colors)(29)

修改后的绘图代码如下:

tm_shape(Neighborhood_MN) +
  tm_polygons(col = "neigh_id", 
              title = "Neighborhoods", 
              palette = extended_colors, 
              labels = legend_labels,
              alpha = 1) +
  # 新增质心编号显示层,可自行调整size参数修改字号
  tm_shape(neigh_centroids) +
  tm_text(text = "neigh_id", size = 0.7, col = "black") +
  tm_legend(show = TRUE) +
  tm_layout("Manhattan Neighborhoods",
            legend.title.size = 1,
            legend.text.size = 0.6,
            legend.position = c("left","top"),
            legend.bg.color = "white",
            legend.bg.alpha = 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:42:00