使用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
相关产品推荐
相关产品推荐

