How to plot a map with ggplot2?

GrIbericPeninsula.png

Administrative maps with R

GrSpainTotal.png

Administrative maps with R

Source: HacerMapaShape.r

Data: datosedad.csv

## -*- ispell-local-dictionary: british  -*-
## Emilio Torres-Manzanera 
## University of Oviedo    
## Time-stamp: "2012-03-18 dom 22:36 emilio on emilio-laptop"

rm(list=ls())
library(sp)
library(rgdal)
library(maptools)
gpclibPermit()
library(ggplot2)
library(splancs)
require(gpclib)

## Download a shapefile with the administrative borders of Spain
## Borrowed from Oscar Perpiñan
## https://r-forge.r-project.org/scm/viewvc.php/drafts/UTMLatLon.R?view=markup&root=solar
## ## Not run:
##    download.file('http://www.gadm.org/data/shp/ESP_adm.zip', 'ESP_adm.zip')
##    unzip('ESP_adm.zip')
## ## End(Not run)


## There are different levels of administrative regions
## Whe choose the level 1, that corresponds to
## Autonomous Communities.
i <- 1
namefilei <- paste('ESP_adm',i, sep="")
spmapesp <- readShapeLines(namefilei) # proj <- CRS('+proj=longlat +ellps=WGS84')
Encoding(levels(spmapesp$NAME_1)) <- "latin1"

## In order to plot with ggplot2, we need fortify the map
mymap <- fortify(spmapesp)
mymap$name <-  spmapesp@data[ as.character(mymap$id), "NAME_1"]
mymap$id <- factor(mymap$id)

## We will only work with regions in Iberic peninsula. We drop 3 regions.
ccaanopeninsula <- c("Islas Baleares", "Islas Canarias", "Ceuta y Melilla")
mymap <- droplevels(mymap[ !(mymap$name %in% ccaanopeninsula),])

## A first plot to see the map
grmap <- ggplot() +
   geom_path( aes( x= long, y =lat, group = group), data = mymap) 

## Save the map.
png("GrIbericPeninsula.png")
grmap
dev.off()

## We read a data file with data about numbers of citizens by groups of age
## Data are obtained from INE http://www.ine.es/
dataage <- read.csv(file="datosedad.csv",sep=";")

## Now, we want a variable named 'name' in both data frames.
## Since names and codes of INE and of GADM are different,
## we have to do a little trick to match both codes
matchnames <- function(name, listofnames,...) {
  require(stringr)
  name <- str_trim(name)
  listofnames <-str_trim(listofnames)
  for( i in c(1:100)/100 ) {
    position <- agrep(pattern=name, x=listofnames, ignore.case = TRUE, max.distance=i, ...)
    if(length(position)) return( position[1] )
  }
}
namesregions <- c(levels(mymap$name),ccaanopeninsula)
idx <- sapply(dataage$nombreine, matchnames, namesregions, value = FALSE)
dataage$name <- factor(namesregions[idx])
dataage[,c("nombreine","name")]

mydata <- dataage

## We save both data frames for future work.
save(mymap, mydata, file="IbericPeninsulaAge.rda")

## We want to plot the total population for each region
## First, we add the variable total to mymap
idx <- match(mymap$name, dataage$name)
mymap$total <- dataage$total[idx]

grmap2 <- ggplot() +
   geom_polygon( aes( x= long, y =lat, group = group, fill=total), data = mymap)

png("GrSpainTotal.png")
grmap2
dev.off()

Author: emilio <emilio@emilio-laptop>

Date: 2012-03-18 22:48:05 CET

HTML generated by org-mode 6.34c in emacs 23