简体   繁体   中英

using ggmap to plot points randomly distributed within boundaries of shape file

Is it possible to use ggplot2 / ggmap to plot geom_points randomly within a given spatial area defined by a shapefile?

I considered geom_jitter, however I need the plots to be randomly distributed and not cross spatial borders.

Sample data shamelessly borrowed from @matthiash here .

library(rgdal)
library(ggmap)

# Get shapefile with Drammen municipality borders
tmpzip<-tempfile()
tmpdir<-tempfile()
dir.create(tmpdir)
download.file("http://www.kartverket.no/Documents/Kart/N50-N5000%20Kartdata/33_N5000_shape.zip",tmpzip)
unzip(tmpzip, exdir=tmpdir)
kommune <- readOGR(dsn=tmpdir, layer="NO_AdminOmrader_pol")
kommune<-kommune[kommune$NAVN=="Drammen",]
kommune<-spTransform(kommune, CRS("+init=epsg:4326"))
dat<-fortify(kommune)

#get the base map
map <- get_map(location = "Drammen",
           maptype = "watercolor", source = "stamen", zoom = 11)

Below code plots the base map with region id 154 from the shapefile plotted on top.

ggmap(map, extent = "normal", maprange = TRUE)+
 geom_polygon(data = dat,
           aes(long, lat, group = group),
           fill = "orange", colour = "red", alpha = 0.2)

What I'd like to do is plot 10 points randomly within the shapefile region defined by dat$id==154

Ok, I sorted it out. The solution is in spsample() in package "raster".

d<-data.frame(id=NA,x=NA,y=NA)
l<-data.frame(id=154,n=10)

for (i in unique(l$id)){
 temp<-spsample(kommune[which(kommune$OBJECTID==i),],n=l[l$id==i,"n"],type="random")
 temp<-as.data.frame(temp)
 temp$id<-i
 d<-rbind(d,temp[,c("id","x","y")])
}
d<-d[-1,] #drop the first empty row

ggmap(map, extent = "normal", maprange = T)+
  geom_polygon(data = dat,
           aes(long, lat, group = group),
           fill = "blue", colour = "yellow", alpha = 0.1)+
  geom_point(aes(x = x, y = y), data = d[which(d$id==154),], alpha = .9,show.legend = T)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM