這裏併入以上提出通過@hrbrmstr & @Rich Pauloo的想法,以及the answer to this question溶液:
步驟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中的結果(我寧願在一個單獨的地理信息系統,以驗證這一點,但我沒有這個計算機上的任何安裝):
# 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"),
[email protected],
by = c("id" = "group"))
# plot
ggplot(spdf,
aes(x = long, y = lat, group = group, alpha = alpha)) +
geom_polygon(color = "black") +
coord_map()
'?ggplot_build' – hrbrmstr
你試過'writeOGR()'? –