2017-11-15 21 views
0

ggplot2/ggmap을 사용하여 shapefile에 정의 된 주어진 공간 영역 내에서 geom_points를 무작위로 플롯 할 수 있습니까?ggmap을 사용하여 모양 파일의 경계 내에 임의로 분포 된 점을 그립니다.

나는 geom_jitter를 고려했다. 그러나 무작위 적으로 분포하고 공간 경계를 넘지 않는 플롯이 필요하다.

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

아래 코드는 위에 그려진 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) 

154

답변

0

확인 날엔 $ 아이디 ==에 의해 정의 된 Shape 파일의 지역 내 10 점을 무작위로 플롯이다, 나는 그것을 정리. 해결책은 "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) 

enter image description here