Created
February 5, 2013 15:09
-
-
Save simonohanlon101/4715010 to your computer and use it in GitHub Desktop.
Create plot of West Africa using ggplot2 and data from Natural Earth repository.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Load relevant pacakges | |
library(ggplot2) | |
library(maptools) | |
library(rgeos) | |
library(plyr) | |
# Download and unzip the Natural Earth Country Polygon data | |
oldwd <- getwd() | |
tmp <- tempdir() | |
setwd(tmp) | |
url <- "http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/cultural/50m-admin-0-countries.zip" | |
dest <- paste(tmp,"\\tmp.zip",sep="") | |
download.file(url,dest) #File is 1.3Mb | |
unzip(dest) | |
# Read in the data to a SpatialPolygonsDataFrame and subset to West African countries | |
wld <- readShapePoly("ne_50m_admin_0_countries") | |
wa <- wld[c(21,22,43,44,81,82,84,144,151,158,160,190,195,213),] | |
# Convert to data.frame for plotting with ggplot2 | |
wa@data$id <- rownames(wa@data) # Explicitly identifies attribute rows by the .dbf offset | |
wa.df <- as.data.frame(wa) | |
gpclibPermit() # required for fortify method if rgeos is unavailable | |
wa.fort <- fortify(wa, region="id") | |
wa.gg <- join(wa.fort, wa.df,by="id") | |
# Create the plot | |
p <- ggplot(wa.gg)+ | |
geom_polygon(aes(long,lat,group=group))+ | |
geom_path(colour="white",aes(long,lat,group=group),size=1.2)+ | |
coord_equal()+ | |
scale_x_continuous(name=expression(paste("Longitude (",degree,")")),limits=c(-18,4),expand=c(0,0))+ | |
scale_y_continuous(name=expression(paste("Latitude (",degree,")")),limits=c(4,17),expand=c(0,0)) | |
print(p) | |
unlink(tmp,recursive=T) | |
setwd(oldwd) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment