2

我需要在 CARTO(又名 cartodb)中导出等高线图,所以我试图以 shapefile 或 geojson 等地理数据文件格式保存这个 stat2density 图表。我可以使用 ggsave 将其保存在 SVG 中,但将其转换为 spdf 或 sf oblejct 会非常有帮助。

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()

任何想法?

4

1 回答 1

2

这是一个结合了上面@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()

shapefile变成了ggplot

于 2017-09-16T09:48:51.277 回答