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?
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:
Step 2. Convert the data frames into a SpatialPolygonsDataFrame object, to be passed to
writeOGR
:Step 3. Save the SpatialPolygonsDataFrame object as a 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):