我需要在 CARTO(又名 cartodb)中导出等高线图,因此我尝试以地理数据文件格式(例如 shapefile 或 geojson)保存此 stat2密度图表。 我可以使用 ggsave 将其保存为 SVG,但将其转换为 spdf 或 sf objct 会非常有帮助。
library(ggplot2)
library(ggmap)
data("crime")
crime<- head(crime,1000)
gg <- ggplot(aes(x = lon, y = lat), data=crime) +
stat_density2d(aes(alpha=..level.., color=..level.., fill=..level..),geom='polygon', bins = 10, size=0.5) +
scale_color_gradient(low = "grey", high = "#444444", guide = F)+
scale_fill_gradient(low = "yellow", high = "red", guide = F)+
scale_alpha( guide = F)+
coord_map()+
ggthemes::theme_map()
有什么想法吗?
最佳答案
这是一个融合了上面 @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 中验证结果(我更愿意在单独的 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()
关于r - 在 shapefile 中保存 ggplot2 coord_map() 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248061/