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

使用ggplot2绘制shp文件时出现‘object 'long' not found’错误

解决读取SHP文件绘图时long对象未找到的错误

问题重现

你编写的读取SHP文件并绘图的代码如下:

library(sf)
library(ggplot2)
library(ggmap)    # for fortifying shapefiles
nc <- st_read("shp/polygons.shp")
#plot(st_zm(nc), max.plot = 1)
shapefile_df <- fortify(nc)
map <- ggplot() +
  geom_path(data = shapefile_df, 
            aes(x=long, y=lat, group = group),
            color = 'gray', fill = 'white', size = .2)

print(map) 

运行时出现错误:

Error in `geom_path()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `FUN()`:
! object 'long' not found
Run `rlang::last_error()` to see where the error occurred.

nc对象的结构截图:
nc对象的sf结构

错误原因

st_read()读取的是sf格式的空间对象,而ggmap包的fortify()函数是为旧版的sp空间对象设计的。用它处理sf对象时,不会生成long、lat、group这些geom_path()需要的字段,因此触发找不到long的错误。

另外,你代码注释里提到了3D绘图,但当前代码是2D的,下面会一并给出3D实现方案。

解决方案

方案1:用ggplot2原生支持的geom_sf()绘图(推荐)

ggplot2已经原生支持sf对象,无需转换,直接用geom_sf()即可完成2D绘图:

library(sf)
library(ggplot2)

# 读取SHP文件
nc <- st_read("shp/polygons.shp")

# 2D绘图
map <- ggplot() +
  geom_sf(data = nc, color = 'gray', fill = 'white', size = .2)

print(map)

方案2:实现3D绘图

如果需要完成3D可视化,可以使用rayshader包(需先安装),将ggplot2的2D图转为3D效果:

library(sf)
library(ggplot2)
library(rayshader)

# 读取SHP文件
nc <- st_read("shp/polygons.shp")

# 先绘制2D基础图
gg_plot <- ggplot() +
  geom_sf(data = nc, color = 'gray', fill = 'white', size = .2)

# 转换为3D可视化(可调整width、height、scale参数优化效果)
plot_gg(gg_plot, multicore = TRUE, width = 5, height = 5, scale = 250)

方案3(不推荐):转换为sp对象再用fortify()

如果一定要保留fortify()的使用方式,需要先把sf对象转为sp对象,但这种方式属于兼容旧代码的过渡方案,不推荐长期使用:

library(sf)
library(ggplot2)
library(ggmap)
library(sp)

nc <- st_read("shp/polygons.shp")
# 转换为sp对象
nc_sp <- as(nc, "Spatial")
# 用fortify转换
shapefile_df <- fortify(nc_sp)

map <- ggplot() +
  geom_path(data = shapefile_df, 
            aes(x=long, y=lat, group = group),
            color = 'gray', fill = 'white', size = .2)

print(map)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:01:36