简体   繁体   English

使用ggmap绘制随机分布在形状文件边界内的点

[英]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? 是否可以使用ggplot2 / ggmap在shapefile定义的给定空间区域内随机绘制geom_points?

I considered geom_jitter, however I need the plots to be randomly distributed and not cross spatial borders. 我考虑了geom_jitter,但是我需要将图随机分布并且不跨越空间边界。

Sample data shamelessly borrowed from @matthiash here . 从@matthiash无耻借用的样本数据在这里

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. 下面的代码从顶部绘制的shapefile中绘制了ID为154的底图。

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 我想做的是在dat $ id == 154定义的shapefile区域内随机绘制10个点

Ok, I sorted it out. 好的,我整理了一下。 The solution is in spsample() in package "raster". 解决方案在软件包“ raster”中的spsample()中。

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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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