2014-01-27 17 views
0

我正在嘗試繪製喬治亞州的奧塞斯特地區。這工作得很好,下面的代碼:地理信息系統在R - 只顯示與其他地區交叉的地區的一部分

setwd("/my/path/") 

library(sp) 
library(maps) 
library(maptools) 
library(ggplot2) 
library(rgdal) 

greg <- readOGR("../GlobalData/GREG/", "GREG", 
       verbose = TRUE, stringsAsFactors = FALSE) 

borders <- readOGR("/path/to/cshapes/", "cshapes", 
        verbose = TRUE, stringsAsFactors = FALSE) 

georgia <- borders[borders$COWCODE == 372,] 
ossetes <- greg[greg$G1ID == 849,] 

georgia.df <- fortify(georgia) 
ossetes.df <- fortify(ossetes) 

tblisi <- [email protected] # access data from the shapefile from here 
tblisi["group"] <- 91.1 

p <- ggplot(georgia.df, aes(x = long, y = lat, group = group)) + 
    geom_polygon(aes(x=long,y=lat,group=group), fill="white", colour="grey") + 
    # Add capital city 
    geom_point(data=tblisi,aes(CAPLONG,CAPLAT),colour="black",size=4) + 
    geom_text(data=tblisi, aes(CAPLONG, CAPLAT, label=CAPNAME),hjust=1, vjust=-0.6) + 
    # Add Ossetes 
    geom_path(data = ossetes.df, aes(x=long,y=lat,group=group), fill="white", colour="grey") + 
    # Styling 
    labs(x=" ", y=" ") + 
    theme_bw() + 
    theme(panel.grid.minor=element_blank(), panel.grid.major=element_blank()) + 
    theme(axis.ticks = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank()) + 
    theme(panel.border = element_blank()) 

p 

返回如下圖:

Map of Georgia with areas for Ossetes

我想這樣做的是隻顯示在格魯吉亞Ossetes 的區域。 但我目前還不知道如何抑制國界以外的地區(直接從第比利斯,由countryborder分開的地區)。

有關我如何做到這一點的任何想法?

+1

也許使用'rgeos :: gIntersection()''剪輯'或'裁剪''ossetes' by'georgia',[如此處演示](http://stackoverflow.com/questions/13982773/crop -for-spatialpolygonsdataframe/13986029#13986029)爲例。 –

回答

3

由於@JoshObrien說,gIntersection(...)是要走的路。

library(sp) 
library(ggplot2) 
library(rgdal) 
library(rgeos) 
setwd("<directory with shapefiles...>") 

greg <- readOGR(dsn=".", layer="GREG", verbose = TRUE, stringsAsFactors = FALSE) 
borders <- readOGR(dsn=".", layer="GEO_adm0", verbose = TRUE, stringsAsFactors = FALSE) 
ossetes <- greg[greg$G1ID == 849,] 
ossetes.df <- fortify(ossetes) 
georgia.df <- fortify(borders) 

intersect <- gIntersection(borders,ossetes) 
intersect.df <- fortify(intersect) 
ggplot()+ 
    geom_path(data=intersect.df, aes(x=long,y=lat,group=group), colour="blue")+ 
    geom_path(data=georgia.df, aes(x=long,y=lat,group=group), colour="red")+ 
    coord_fixed() 

BTW:在未來,請提供鏈接到你的shape文件。 GREGGeorgia

相關問題