[R] Fine Tuning Country Map
Lorenzo Isella
lorenzo.isella at gmail.com
Mon Aug 13 23:33:46 CEST 2012
Dear All,
Please see the short script at the end of the email, which I assembled
looking for bits and pieces on the web.
It essentially does what I need: it plots several countries as a
color-coded map.
I just would like to fine-tune a bit the final image, in particular
(1) Select my own colors for "painting" the countries (i.e. associate
manually a color to every level)
(2) Be able to control the position of the legend and the size of the
character used in the legend itself.
Any suggestion is welcome.
Cheers
Lorenzo
################################################à
## you will need the sp-package
library('sp')
## load a file from GADM (you just have to specify the countries "special
part" of the file name, like "ARG" for Argentina. Optionally you can
specify which level you want to have
loadGADM <- function (fileName, level = 0, ...) {
load(url(paste("http://gadm.org/data/rda/", fileName, "_adm", level,
".RData", sep = "")))
gadm
}
## the maps objects get a prefix (like "ARG_" for Argentina)
changeGADMPrefix <- function (GADM, prefix) {
GADM <- spChFIDs(GADM, paste(prefix, row.names(GADM), sep = "_"))
GADM
}
## load file and change prefix
loadChangePrefix <- function (fileName, level = 0, ...) {
theFile <- loadGADM(fileName, level)
theFile <- changeGADMPrefix(theFile, fileName)
theFile
}
## this function creates a SpatialPolygonsDataFrame that contains all maps
you specify in "fileNames".
## E.g.:
## spdf <- getCountries(c("ARG","BOL","CHL"))
## plot(spdf) # should draw a map with Brasil, Argentina and Chile on it.
getCountries <- function (fileNames, level = 0, ...) {
polygon <- sapply(fileNames, loadChangePrefix, level)
polyMap <- do.call("rbind", polygon)
polyMap
}
spdf <- getCountries(c("ITA","CHE","FRA", "DEU","BEL", "LUX"))
AP <- c("SLS","SLS", "NWS", "NSLS", "NSLS", "NWS")
spdf$AP <- as.factor(AP)
png("many-countries.png")
## print(spplot(spdf, "NAME_ENGLI"))
print(spplot(spdf, "AP"))
## plot(spdf)
dev.off()
More information about the R-help
mailing list