在1张地图上绘制多条线

时间:2015-08-09 15:37:37

标签: r google-maps ggplot2 ggmap

我想在1张地图上绘制2条不同的路线。这是我作为例子的代码:

### Plot 2 routes on 1 map

# libraries

library(ggmap)
library(ggplot2)

# plot map

basicmap <- get_map(location = c(lon = 3, lat = 50),
                    zoom = 12,
                    maptype = "roadmap",
                    source = "google",
                    color = "color")  #completely random location
basicmap <- ggmap(basicmap)

# determine routes

routes <- data.frame(from = c("Rocquigny", "Nurlu"),
                     to = c("Heudicourt","Longavesnes"),
                     stringsAsFactors = FALSE)

# calculate routes

calculationroute <- function(startingpoint, stoppoint) {
  route(from = startingpoint,
        to = stoppoint,
        mode = "bicycling",
        structure = "route")
}
  #this function calculates the route

calculatedroutes <- mapply(calculationroute,
                           startingpoint = routes$from,
                           stoppoint = routes$to,
                           SIMPLIFY = FALSE)
  #calculate the 2 routes

# draw routes

drawroute <- function(route) {
  geom_path(aes(data = route,
                x = lon,
                y = lat))
}
  #this functions draws the route

extendedmap <- basicmap + lapply(X = calculatedroutes,
                                 FUN = drawroute)
plot(extendedmap)
  #draw the routes

所以这些是我采取的步骤:

  1. 创建背景地图
  2. 我创建了一个包含2条路线的起点和终点的数据框
  3. 使用ggmap我计算这些路线的分段。
  4. 我尝试在背景地图上绘制路线
  5. 可悲的是,最后一步失败并发生此错误:

    Don't know how to automatically pick scale for object of type function. Defaulting to continuous
    Error in data.frame(x = c(2.89030838012694, 3.11003494262694, 2.89030838012694,  : 
      arguments imply differing number of rows: 4, 0
    

    我进行了搜索,this previous question想要做同样的事情。他最终选择的解决方案使用了for循环,而我宁愿使用lapply来保持代码的一致性。

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,label循环有效,但您可以采用更for种方式执行此操作。首先,我们需要更改您的ggplot调用,因为范围对于您的某条路线来说不够大:

ggmap

计算出路线后,我们可以制作一个长数据框:

basicmap <- get_map(location = c(lon = 3, lat = 50),
                    zoom = 8,
                    maptype = "roadmap",
                    source = "google",
                    color = "color")  #completely random location
basicmap <- ggmap(basicmap)

然后对do.call(rbind.data.frame, lapply(names(calculatedroutes), function(x) { cbind.data.frame(route=x, calculatedroutes[[x]], stringsAsFactors=FALSE) })) -> long_routes 使用group美学:

geom_path

enter image description here