这是一个结合了上面@hrbrmstr & @Rich Pauloo 提出的想法的解决方案,以及这个问题的答案:
步骤 1。从 ggplot 对象中提取相关数据:
library(dplyr)
# return a list of data frames (each data frame contains coordinates for one contour);
# note that there may be multiple contours at the same alpha / colour / fill,
# hence the need to split by group rather than by these aesthetic mappings.
dg <- layer_data(gg) %>%
select(group, x, y) %>%
split(.$group) %>%
lapply(function(d){d[,-1]})
步骤 2。将数据帧转换为 SpatialPolygonsDataFrame 对象,以传递给writeOGR
:
library(sp)
# convert each data frame to a Polygon class object
polygons <- lapply(dg, Polygon)
# convert each Polygon class object to Polygons class object
polygons <- lapply(seq_along(polygons),
function(i){
Polygons(list(polygons[[i]]),
ID = names(dg)[i])
})
# convert list of Polygons class object to one SpatialPolygons object
polygons <- SpatialPolygons(polygons)
# convert SpatialPolygons object to SpatialPolygonsDataFrame object
polygons <- SpatialPolygonsDataFrame(polygons,
data = layer_data(gg) %>%
select(group, alpha, colour, fill) %>%
unique(),
match.ID = "group")
步骤 3。将 SpatialPolygonsDataFrame 对象保存为 shapefile:
rgdal::writeOGR(obj = polygons,
dsn = getwd(), # or wherever you wish to store it
layer = "filename", # or whatever you wish to name it
driver = "ESRI Shapefile")
在 R 中验证结果(我宁愿在单独的 GIS 程序中验证这一点,但我没有在这台计算机上安装任何程序):
# read the shapefile back into R
sp <- rgdal::readOGR(dsn = getwd(),
layer = "filename")
# fortify as a data frame
spdf <- left_join(broom::tidy(sp, region = "group"),
sp@data,
by = c("id" = "group"))
# plot
ggplot(spdf,
aes(x = long, y = lat, group = group, alpha = alpha)) +
geom_polygon(color = "black") +
coord_map()