2017-09-15 73 views
1

我需要在CARTO(aka cartodb)中導出等值線圖,所以我試圖將這個stat2density圖表保存爲shapefile或geojson等地理數據文件格式。 我可以用ggsave將它保存在SVG中,但將它轉換爲spdf或sf oblejct會非常有幫助。在shapefile中保存ggplot2 coord_map()圖表

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

任何想法?

+3

'?ggplot_build' – hrbrmstr

+1

你試過'writeOGR()'? –

回答

1

這裏併入以上提出通過@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() 

shapefile turned ggplot

+0

太棒了!它完美地工作 – andriatz