Save a ggplot2 coord_map() chart in shapefile

守給你的承諾、 提交于 2019-12-22 17:05:25

问题


i need to export a contour map in CARTO (aka cartodb), so i'm trying to save this stat2density chart in a geodata file format like shapefile or geojson. I'm able to save it in SVG with ggsave, but would be very helpful to convert it in a spdf or 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()

Any idea?


回答1:


Here's a solution that incorporates the ideas proposed by @hrbrmstr & @Rich Pauloo above, as well as the answer to this question:

Step 1. Extract the relevant data from the ggplot object:

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]})

Step 2. Convert the data frames into a SpatialPolygonsDataFrame object, to be passed to 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")

Step 3. Save the SpatialPolygonsDataFrame object as a 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")

Verifying the results in R (I would have preferred to verify this in a separate GIS programme, but I don't have any installed on this computer):

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



来源:https://stackoverflow.com/questions/46248061/save-a-ggplot2-coord-map-chart-in-shapefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!