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

如何在R中基于另一数据集的行列精确匹配为地图数据新增高亮列?

解决美国地图县精确高亮的问题

问题描述

我想要制作一幅美国地图,高亮显示特定的县。尝试用mutate()和case_when(),基于另一数据集的县列表,在县地图数据中新增一列标记该县是否需要高亮。但运行代码后,不该被高亮的县(如明尼苏达州的莱克县)也被高亮了,希望实现州和县的精确行匹配(仅高亮俄亥俄州的莱克县,而非明尼苏达州的)。

原代码:

county.map <- map_data("county")

df <- data.frame(state=c("minnesota", "ohio", "west virginia"), county=c("olmsted", "lake", "kanawha"))

county.map.highlight <- county.map %>%
                mutate(highlight = case_when(region %in% df$state &
                                subregion %in% df$county ~"Yes",
                            TRUE ~ "No"))
ggplot(county.map.highlight) +
geom_polygon(county.map.highlight,
        mapping = aes(x= long,
                y=lat,
                group=group,
                fill=highlight),
        color="black")

问题原因

原代码逻辑是“州在目标列表里 且 县在目标列表里”,这会错误匹配到所有属于目标州的目标县、以及所有属于目标县的目标州——比如明尼苏达州是目标州,莱克县是目标县,所以明尼苏达州的莱克县会被误标记为高亮。

解决方案

需要把州和县的组合作为整体匹配,而非分开判断,以下是两种可行方法:

方法1:用interaction()生成唯一组合标识

通过interaction(region, subregion)生成州+县的唯一字符串,再和df中对应的组合做匹配:

library(ggplot2)
library(dplyr)

county.map <- map_data("county")

df <- data.frame(state=c("minnesota", "ohio", "west virginia"), county=c("olmsted", "lake", "kanawha"))
# 生成需要高亮的州-县组合
target_pairs <- interaction(df$state, df$county, sep = "_")

county.map.highlight <- county.map %>%
  mutate(
    county_pair = interaction(region, subregion, sep = "_"),
    highlight = case_when(
      county_pair %in% target_pairs ~ "Yes",
      TRUE ~ "No"
    )
  )

ggplot(county.map.highlight) +
  geom_polygon(
    mapping = aes(x = long, y = lat, group = group, fill = highlight),
    color = "black"
  ) +
  scale_fill_manual(values = c("Yes" = "red", "No" = "lightgray")) # 可选:自定义高亮颜色

方法2:用left_join()关联表标记

通过关联地图数据和目标县列表,直接标记高亮状态:

library(ggplot2)
library(dplyr)

county.map <- map_data("county")

df <- data.frame(state=c("minnesota", "ohio", "west virginia"), county=c("olmsted", "lake", "kanawha"))

county.map.highlight <- county.map %>%
  left_join(df, by = c("region" = "state", "subregion" = "county")) %>%
  mutate(highlight = ifelse(!is.na(county), "Yes", "No"))

ggplot(county.map.highlight) +
  geom_polygon(
    mapping = aes(x = long, y = lat, group = group, fill = highlight),
    color = "black"
  ) +
  scale_fill_manual(values = c("Yes" = "red", "No" = "lightgray"))

说明

两种方法都能实现州和县的精确匹配:

  • 方法1通过组合字符串生成唯一标识,适合快速判断;
  • 方法2通过表关联实现,逻辑更直观,也方便后续扩展其他数据字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:43:25