plotting shape file in ggplot2

Hammao picture Hammao · Feb 1, 2016 · Viewed 10k times · Source

I'm trying to figure out how to display my complete map in gglot2 including the island Both r_base and tmap were able to display the islands but ggplot2 couldn't differentiate the island from the rest of the waterbody... enter image description here.

My question is how to make the Islands appear in ggplot2?

See the code i used below.

library(ggplot2)
library (rgdal)
library (rgeos)
library(maptools)
library(tmap)

Loading the Persian Gulf shape fill referred to as iho

PG <- readShapePoly("iho.shp")

the shape file is available here

http://geo.vliz.be:80/geoserver/wfs?request=getfeature&service=wfs&version=1.0.0&typename=MarineRegions:iho&outputformat=SHAPE-ZIP&filter=%3CPropertyIsEqualTo%3E%3CPropertyName%3Eid%3C%2FPropertyName%3E%3CLiteral%3E41%3C%2FLiteral%3E%3C%2FPropertyIsEqualTo%3E

plot with r_base

Q<-plot(PG)

Corresponds to figure A

Ploting with tmap

qtm(PG)

Corresponds to figure B

convert to dataframe

AG <- fortify(PG)

Plot with ggplot2

ggplot()+ geom_polygon(data=AG, aes(long, lat, group = group), colour = alpha("darkred", 1/2), size = 0.7, fill = 'skyblue', alpha = .3)

Corresponds to figure C

Answer

admccurdy picture admccurdy · Feb 1, 2016

You need to tell ggplot you want the holes filled in with a different color..for example:

ggplot()+ geom_polygon(data=AG, aes(long, lat, group = group, fill = hole), colour = alpha("darkred", 1/2), size = 0.7) + scale_fill_manual(values = c("skyblue", "white")) + theme(legend.position="none")

Also try readOGR() function from the rgdal package instead of readShapePoly() it keeps all the projection and datum information when you read the shape file.