0

I am trying to plot the area of Ossetes in Georgia. This works fine, the following code:

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 <- georgia@data # 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

returns the following graph:

Map of Georgia with areas for Ossetes

What I would like to do is show only the area of Ossetes in Georgia. But I have currently no idea how to supress the area that is outside of the country borders (the part straight up from Tblisi, parted by the countryborder).

Any ideas on how I could do this?

LukasKawerau
  • 1,071
  • 2
  • 23
  • 42
  • 1
    Maybe use `rgeos::gIntersection()` to "clip" or "crop" `ossetes` by `georgia`, [as demonstrated here](http://stackoverflow.com/questions/13982773/crop-for-spatialpolygonsdataframe/13986029#13986029) for example. – Josh O'Brien Jan 27 '14 at 15:43

1 Answers1

3

As @JoshObrien says, gIntersection(...) is the way to go.

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: In future, please provide links to your shapefiles. GREG Georgia

jlhoward
  • 58,004
  • 7
  • 97
  • 140