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

如何在R语言中为加州特定县(弗雷斯诺等)着色绘制地图

给加州特定县上色的解决方案

核心思路是给县数据添加标记列,区分需要高亮的县和普通县,再通过这个列映射填充色,避免全局改变颜色。

步骤1:修正原始代码的语法错误

原始代码中counties <- map_data("county") ca_county <- counties %>% filter(region == "california")一行缺少换行,会导致报错,先拆分修正。

步骤2:添加高亮标记列

在ca_county数据框中新增一列,标记出需要着色的县(注意subregion中的县名是小写、空格分隔格式,必须和数据中的值完全匹配):

# 定义需要高亮的县列表
target_counties <- c("fresno", "san joaquin", "monterey")

# 给ca_county添加高亮标记列
ca_county <- ca_county %>%
  mutate(highlight = ifelse(subregion %in% target_counties, "highlight", "normal"))

步骤3:修改ggplot代码实现指定着色

在绘制县级图层时,通过highlight列映射填充色,同时设置颜色方案:

# 安装并加载必要包
install.packages(c("maps", "mapdata", "tidyverse", "viridis"))
library(tidyverse)
library(mapdata)
library(maps)
library(viridis)

# 获取州和县数据
states <- map_data("state")
ca_df <- states %>% filter(region == "california")

counties <- map_data("county")
ca_county <- counties %>% filter(region == "california")

# 添加高亮标记
target_counties <- c("fresno", "san joaquin", "monterey")
ca_county <- ca_county %>%
  mutate(highlight = ifelse(subregion %in% target_counties, "highlight", "normal"))

# 绘制地图
ca_base <- ggplot(data = ca_df, aes(x = long, y = lat, group = group)) + 
  coord_quickmap() + 
  geom_polygon(color = "black", fill = "gray")

ca_base + theme_void() + 
  # 绘制县级图层,用highlight列映射填充色
  geom_polygon(data = ca_county, aes(fill = highlight, group = group), color = "white") + 
  # 设置填充颜色:高亮县用指定色,普通县保持灰色
  scale_fill_manual(values = c("highlight" = "#E63946", "normal" = "gray")) +
  # 隐藏图例(按需选择)
  guides(fill = FALSE) +
  labs(title = "California Counties",
       subtitle = "Fresno, San Joaquin, and Monterey Counties highlighted")

关键说明

  • subregion中的县名是小写、空格分隔格式,比如"san joaquin"而非"San Joaquin",必须和数据值完全匹配才能正确筛选。
  • 通过mutate创建的highlight列,能精准控制特殊县的填充色,其余县保持默认灰色。
  • 若需要其他配色,可修改scale_fill_manual中的values参数,比如替换为viridis色系的颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:45:20