如何使用for循环生成每次突出显示不同部分的地图?

时间:2015-08-13 14:36:48

标签: r for-loop dictionary

我想在R中生成一组地图,所有地图都具有相同的背景(关注欧洲)但是每个地图都有一个欧盟国家以另一种颜色突出显示。我似乎无法弄清楚如何编写for循环来获得...

这是我的代码:

require(rgdal)

setwd(...) #where I have my GIS shapefile
world <- readOGR(dsn = ".", layer = "TM_WORLD_BORDERS-0.2")

#Subset European countries

#List of "european" countries + shapefile
europe <- c("Russia", "Isle of Man", "Channel Islands", "Faroe Islands", 
            "France", "Denmark", "Iceland", "Germany", "Romania", "Poland", "Portugal", 
            "United Kingdom", "Spain", "Sweden", "Lithuania", "Ireland", "Italy", 
            "Netherlands", "Norway", "Ukraine", "Latvia", "Estonia", "Finland", 
            "Bulgaria", "Belgium", "Montenegro", "Serbia and Montenegro", "Slovenia",
            "Albania", "Greece", "Croatia", "Malta")
europe <- subset(world, NAME %in% europe)

#List of countries in the EU + shapefile
EU <- c("Isle of Man", "Channel Islands", "Faroe Islands", "France",
        "Denmark", "Germany", "Romania", "Poland", "Portugal", "Spain", "Sweden",
        "Lithuania", "Ireland", "Italy", "Netherlands", "Ukraine", "Latvia", "Estonia",
        "Finland", "Bulgaria", "Belgium", "Montenegro", "Serbia and Montenegro",
        "Slovenia", "Albania", "Greece", "Croatia", "Malta")
EU <- subset(europe, NAME %in% EU)

#Generate one map per highlighted country

eucountries <- unique(europe$NAME)

for(i:length(eucountries))
    {
      print(i)
      png(paste(i,".png",sep=""), 200, 200)
      map("world", ylim=c(35,70), xlim=c(-20,45), col="#BFBFBF", fill=TRUE)
      plot(eucountries, add=TRUE, col="#769EB2", namesonly=TRUE)
      dev.off()
    }

我想为每个国家生产一个png。每个png都会有一个以不同颜色突出显示的特定国家/地区。每次都会绘制完整的地图。

2 个答案:

答案 0 :(得分:0)

感谢vpipkt的评论表明map()$names确实提供了一系列事物(我怀疑的多边形)的名称,我可以提出一个更加优雅的解决方案:

  • 为那些名为“国家/地区”的多边形构建索引
  • 使用该信息构建颜色矢量以为国家/地区着色
  • 注意:地图包装提供的边框似乎过时了,例如南斯拉夫

# library
library(maps)

# options
old <- par()$mar
par("mar"=c(0,0,0,0))
YLIM <- c(35,70)
XLIM <- c(-20,45)

# plotting
  for(country in c("Germany", "Ireland", "Spain", "Greece", "Denmark", "Yugoslavia") ) 
  {
    polygon_names <- map("world", ylim=YLIM, xlim=XLIM)$names
    index  <- grep(country, polygon_names)
    colvec <- rep("white", length(polygon_names))
    colvec[index] <- "red"
    png(paste0(country,".png"))
      map("world", ylim=YLIM, xlim=XLIM, col=colvec, fill=TRUE)
    dev.off()
  }

# resetting options
par("mar"=old)

enter image description here

答案 1 :(得分:0)

在你的循环中,尝试

plot(eucountries[i], add=TRUE, col="#769EB2", namesonly=TRUE)

代替您当前的plot来电。请注意eucountries的子集。