在一张地图上绘制多条线

Plotting multiple lines on 1 map

我想在 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. 我尝试在背景地图上绘制路线

遗憾的是,最后一步失败并出现此错误:

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

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

正如我在评论中所说,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

然后为 geom_path 使用 group 美学:

basicmap + geom_path(data=long_routes, 
                     aes(x=lon, y=lat, group=route, color=route),
                     size=1)