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

使用sf包绘制地图:如何替代已弃用的fortify函数?

解决sf对象结合ggplot2绘图的问题

你遇到的问题根源在于**fortify()**是针对旧的sp对象设计的,现在你用的是sf对象,完全不需要这一步转换,直接用ggplot2的geom_sf()就能轻松绘图,而且这是当前处理空间数据的标准方式。

修改后的完整代码:

# 加载所需包
library(sf)
library(ggplot2)
library(httr) # 用于GET和stop_for_status函数

url <- "https://gist.githubusercontent.com/hrbrmstr/91ea5cc9474286c72838/raw/f3fde312c9b816dff3994f39f2bcda03209eff8f/continents.json"
# 下载并保存文件
stop_for_status(GET(url, write_disk("continents.json")))
# 读取为sf对象
continents <- geojson_sf("continents.json")
# 筛选目标大洲
continents.f <- continents[continents$CONTINENT %in% c("North America", "Central America", "South America"),]

# 用geom_sf绘图,无需fortify转换
gg <- ggplot(data = continents.f) +
  geom_sf(fill = "#ffffff", color = "black", size = 0.15) +
  # 用coord_sf设置地图范围,比lims更适配空间数据
  coord_sf(xlim = c(-110, -20), ylim = c(-60, 20))
gg

关键修改点:

  • 移除了fortify()步骤:sf对象本身就包含ggplot2需要的空间信息,不需要转换为传统的data.frame格式。
  • 替换geom_map()为geom_sf():这是ggplot2专门为sf空间对象设计的几何图层,能直接识别sf对象的空间属性。
  • 用coord_sf()替代lims():coord_sf()是专门为地图设置坐标范围的函数,比通用的lims()更适合空间数据,避免出现坐标变形的问题。

如果还需要按大洲分组设置不同样式,直接在geom_sf()的aes()里绑定CONTINENT字段即可,比如:

ggplot(data = continents.f) +
  geom_sf(aes(fill = CONTINENT), color = "black", size = 0.15) +
  coord_sf(xlim = c(-110, -20), ylim = c(-60, 20)) +
  scale_fill_brewer(palette = "Set2")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:42:51