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

R语言tigris包:非ZCTA区域可视化图例添加需求

解决ggplot绘制ZCTA地图时添加“无数据”图例项的问题

先修正数据源代码的小问题

你当前的代码中,property_zip是筛选后的数据集,但后续left_join用的是原始property,会导致多余列被合并,建议修正为:

zcta_geo <- tigris::zctas(class = "sf", year=2020, cb=TRUE, progress_bar=FALSE)

property_zip <- property %>% select(c("zcta","mean_wind","mean_fire"))

zcta_geo$ZCTA5CE20 <- as.numeric(zcta_geo$ZCTA5CE20)

# 改为用筛选后的property_zip进行连接
zip_geo <- left_join(zcta_geo, property_zip, by=c("ZCTA5CE20"="zcta"))

zip_geo <- zip_geo %>% filter(state_fips<=56)

方法1:拆分数据+双图层+ggnewscale添加独立图例

这种方法将有数据和无数据区域分开绘制,通过ggnewscale添加独立的“无数据”图例项,清晰直观:

  1. 安装并加载所需包:
install.packages(c("ggplot2", "dplyr", "sf", "ggnewscale", "viridis"))
library(ggplot2)
library(dplyr)
library(sf)
library(ggnewscale)
library(viridis)
  1. 拆分数据集为有数据和无数据两部分:
# 筛选有mean_wind数据的区域
zip_geo_has_data <- zip_geo %>% filter(!is.na(mean_wind))
# 筛选无数据的区域
zip_geo_no_data <- zip_geo %>% filter(is.na(mean_wind))
  1. 绘制地图并添加自定义图例:
ggplot() +
  # 先画有数据的区域,用渐变填充
  geom_sf(data = zip_geo_has_data, aes(fill = mean_wind), color = "gray80", linewidth = 0.1) +
  # 设置渐变填充的配色和名称
  scale_fill_viridis_c(name = "平均风速", option = "plasma") +
  
  # 添加新的填充比例尺,避免和之前的渐变冲突
  new_scale_fill() +
  
  # 画无数据区域,映射fill为"无数据"
  geom_sf(data = zip_geo_no_data, aes(fill = "无数据"), color = "gray80", linewidth = 0.1) +
  # 设置无数据区域的填充色为白色,自定义图例
  scale_fill_manual(name = "", values = c("无数据" = "white")) +
  
  # 调整主题,简化地图元素
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank()
  )

方法2:处理NA值为分类变量+混合图例

如果希望将“无数据”整合到同一个图例中,可以把连续变量转为包含“无数据”的分类变量:

  1. 转换数据类型:
zip_geo <- zip_geo %>%
  mutate(
    mean_wind_cat = case_when(
      is.na(mean_wind) ~ "无数据",
      mean_wind < quantile(mean_wind, 0.2, na.rm=T) ~ "低",
      mean_wind < quantile(mean_wind, 0.8, na.rm=T) ~ "中",
      TRUE ~ "高"
    ),
    # 指定因子顺序,确保"无数据"在图例最前面
    mean_wind_cat = factor(mean_wind_cat, levels = c("无数据", "低", "中", "高"))
  )
  1. 绘制地图:
ggplot(zip_geo) +
  geom_sf(aes(fill = mean_wind_cat), color = "gray80", linewidth = 0.1) +
  # 自定义填充色,白色对应无数据
  scale_fill_manual(
    name = "平均风速",
    values = c("无数据" = "white", "低" = "#440154", "中" = "#21908C", "高" = "#FDE725")
  ) +
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank()
  )

关键说明

  • 方法1适合保留连续变量的渐变展示,同时清晰标注无数据区域;
  • 方法2适合将连续变量分组为分类,把无数据作为其中一类,整合到同一个图例;
  • 两种方法都通过手动设置填充色为白色,明确对应“无数据”,解决西部空白区域的图例说明问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:28:28