首页 > 解决方案 > Shapefile 未正确填充 geom_polygon,与 QGIS/ArcMap 不一致

问题描述

我已经通过 readOGR 将世界海洋的 shapefile 从 Natural Earth 导入到 R。当我尝试在 ggplot 中渲染它时,它会填满北美和南美的土地。该行为与 QGIS 和 ArcMap 不一致,两者都可以很好地渲染和填充 shapefile。有任何想法吗?

download.file("https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/physical/ne_50m_ocean.zip" , destfile="./ne_50m_ocean.zip")
system("unzip ./ne_50m_ocean.zip")
wrld <- readOGR(dsn=getwd(),layer="ne_50m_ocean")
wrld <- tidy(wrld)
ggplot() + geom_polygon(data = wrld, aes(x = long, y = lat, group = group), colour = "black", fill = "blue")

RStudio 渲染截图

QGIS 渲染截图

标签: rggplot2rgdal

解决方案


我能够使用 read_sf() 而不是 readOGR() 解决这个问题,然后调整 ggplot 代码以适应。也适用于我的工作流程的下一点,其中涉及使用 fastize() 对 sf 对象进行光栅化,用于掩码海洋层(包含的简化演示代码,以防对其他人有用):

#get data
download.file("https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/physical/ne_50m_ocean.zip" , destfile="./ne_50m_ocean.zip")
system("unzip ./ne_50m_ocean.zip")
wrld <- read_sf(dsn=getwd(),layer="ne_50m_ocean")

#plot sf object
ggplot() + geom_sf(data=wrld, colour = "black", fill = "blue")

#rasterize sf object
r <- raster(ncol=720, nrow=360) 
extent(r) <- extent(wrld) 
rp <- fasterize(wrld, r)
ocean <- as.data.frame(rasterToPoints(rp))

#plot raster object
ggplot() + geom_tile(data=ocean,aes(x=x,y=y),fill="white")


推荐阅读