[This article was first published on R snippets, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Last week I used grImport for the first time. I decided to try perform another exercise using it. The task was to add voivodeship division of Poland.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Standard R maps do not contain such a division. I have found it on r-forge in package mapoland based on ESRI shape files, but I wanted to import such a map from SVG file which can be found on Wikipedia. As last time SVG file has to be converted do PS first. Here is a comparison of both maps showing that the import worked quite well.
And this is the code I have used:
library(grImport)< o:p>
PostScriptTrace(“Wojewodztwa.ps”)< o:p>
voiv <- readPicture(“Wojewodztwa.ps.xml”)< o:p>
broken.voiv <- explodePaths(voiv)< o:p>
#extracting voivodeship ‘PictureStrokes’< o:p>
xpath <- ypath <- list()< o:p>
sel <- c(2,4,6,8,20,22,24,28,30,32,34,36,38,41,44,46)< o:p>
for (i in seq(along = sel)) {< o:p>
xpath[[i]] <- broken.voiv[[sel[i]]]@paths$path@x< o:p>
ypath[[i]] <- broken.voiv[[sel[i]]]@paths$path@y< o:p>
}< o:p>
#adding Wolin island to zachodniopomorskie< o:p>
xpath[[2]] <- c(broken.voiv[10]@paths$path@x[c(39:1, 95:40)],< o:p>
xpath[[2]])< o:p>
ypath[[2]] <- c(broken.voiv[10]@paths$path@y[c(39:1, 95:40)],< o:p>
ypath[[2]])< o:p>
library(mapoland)< o:p>
pl <- getShape(“voiv”)< o:p>
#functions rescaling paths to mapoland map size< o:p>
transx <- function(x) {< o:p>
old <- c(min(sapply(xpath,min)), max(sapply(xpath,max)))< o:p>
new <- pl@bbox[1,]< o:p>
((x – old[1]) / (old[2] – old[1])) * (new[2] – new[1])< o:p>
+ new[1]< o:p>
}< o:p>
transy <- function(y) {< o:p>
old <- c(min(sapply(ypath, min)), max(sapply(ypath, max)))< o:p>
new <- pl@bbox[2,]< o:p>
((y – old[1]) / (old[2] – old[1])) * (new[2] – new[1])< o:p>
+ new[1]< o:p>
}< o:p>
plot(pl, lwd = 4)< o:p>
for (i in seq(along = sel)) {< o:p>
lines(transx(xpath[[i]]), transy(ypath[[i]]), col = “red”)< o:p>
}< o:p>
To leave a comment for the author, please follow the link and comment on their blog: R snippets.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.