ggplot map:“for”循环只添加最终的地图图层

时间:2016-11-29 14:46:21

标签: r for-loop ggplot2 mapping gis

之前已经提出过类似的问题,但是要将一个数据框的不同列的数据添加到图中。 Link to the question

就我而言,我想将新的地图图层(如果它们存在于全局环境中)添加到带有“for”循环的最终地图中。

使用现在的代码,只有最后一层(点)被绘制到地图上,而不是线图层:

rm(list = ls())  
library(OpenStreetMap)
library(ggplot2)
library(sp)

### The base layer map
map <- OpenStreetMap::openmap(c(55.8759, -4.2946), c(55.8638, -4.2776), type="osm")
map <- openproj(map)
myMap <- ggplot2::autoplot(map)

### Create some custom map files
# Some spatial point
new_shapefile <- data.frame(long = -4.290, lat = c(55.868, 55.872))
sp::coordinates(new_shapefile) <- c("long", "lat")
sp::proj4string(new_shapefile) <- sp::CRS("+init=epsg:4326")

# Some spatial line
x <- c(-4.290,-4.285)
y <- c(55.868,55.868)
new_line <- SpatialLines(list(Lines(Line(cbind(x,y)), ID="a")))
new_line = SpatialLinesDataFrame(new_line, data.frame(Z = c("Road"), row.names = c("a")))


addLayer <- function(){
  glob <- globalenv()
  customFiles <- data.frame(ls(pattern = "^(?i)new", envir = glob))
  colnames(customFiles) <- "X"
  customFiles$X <- as.character(customFiles$X)
  for(i in 1:length(customFiles$X)){
    plot <- myMap
    gg.data <- get(paste(customFiles$X[i]))
    if(grepl("^SpatialPolygons", class(get(paste(customFiles$X[i])))) == TRUE){
      plot <- plot + geom_polygon(data = gg.data, aes(long, lat, group= group))
    }
    if(grepl("^SpatialLines", class(get(paste(customFiles$X[i])))) == TRUE){
      plot <- plot + geom_path(data = gg.data, aes(long, lat, group= group))
    }
    if(grepl("^SpatialPoints", class(get(paste(customFiles$X[i])))) == TRUE){
      plot <- plot + geom_point(data = data.frame(coordinates(gg.data)), aes(long, lat))
     }
  }
  print(plot)
}


### Run the function
addLayer()

enter image description here

由于我不能使用melt来解决这个问题,正如上一个问题中所述:是否还有其他方法可以在“for”循环中绘制所有图层?

1 个答案:

答案 0 :(得分:1)

您当前正在循环的每次迭代开始时启动基本映射,这将替换您在上一次迭代中所做的plot。在开始循环之前启动基本地图,以将所有图层添加到同一个地图。

addLayer <- function(){
  glob <- globalenv()
  customFiles <- data.frame(ls(pattern = "^(?i)new", envir = glob))
  colnames(customFiles) <- "X"
  customFiles$X <- as.character(customFiles$X)
  plot <- myMap
  for(i in 1:length(customFiles$X)){
  gg.data <- get(paste(customFiles$X[i]))
  if(grepl("^SpatialPolygons", class(get(paste(customFiles$X[i])))) == TRUE){
      plot <- plot + geom_polygon(data = gg.data, aes(long, lat, group= group))
    }
    if(grepl("^SpatialLines", class(get(paste(customFiles$X[i])))) == TRUE){
      plot <- plot + geom_path(data = gg.data, aes(long, lat, group= group))
    }
    if(grepl("^SpatialPoints", class(get(paste(customFiles$X[i])))) == TRUE){
      plot <- plot + geom_point(data = data.frame(coordinates(gg.data)), aes(long, lat))
     }
  }
  print(plot)
}