如何在R中绘制多种颜色的折线?

时间:2017-02-22 11:50:15

标签: r google-maps leaflet google-directory-api

我正在研究R中的自定义路线规划器。我正在使用Google Maps Directions API的输出。我想在两个地方之间的地图上显示路线。到目前为止,一切都很顺利。唯一的问题是我不知道如何根据目前的速度为路线提供多种颜色。我在互联网上搜索了几天,但找不到符合我目标的东西。这就是我发这篇文章的原因。

This is how my polyline data frame looks like:

然后我在Leafet中使用以下代码将其可视化:

#install.packages("leaflet")
library(leaflet)


pal <- colorNumeric(
palette = unique(polyline$Col),
domain = polyline$Speed,
na.color = "#FFFFFF"
)
rm(map)
map <- leaflet()
map <- addTiles(map)
a <- 1
for(a in length(unique(polyline$Step_ID))){


map <- addPolylines(map,lng = polyline$Lon, 
           lat = polyline$Lat,
           data = polyline[polyline$Step_ID==a,],
           color = polyline$col)
a <- a + 1
}
map <- addLegend(map,"bottomright", pal = pal, values = polyline$Speed,
        title = "Speed",
        opacity = 1)
map

到目前为止,我认为你必须创建多个PolyLines(如果我错了,请纠正我)在路线中绘制多种颜色。这就是为什么我做了一个for循环,将PolyLine添加到地图中。

This is how my visualization looks like

Everthing就是它的需要。唯一的问题是线的着色。我希望像Google一样对流量进行着色。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

要完全复制您的问题,您需要向我们提供polyline的实际数据(即,不是屏幕截图)。在那之前,我将创建自己的数据集,并向您展示如何创建彩色线条。

而且,当您使用Google的API获取路线时,我假设您已拥有API密钥,因此我将向您展示如何使用我的googleway包

来做到这一点
library(googleway)

api_key <- "your_api_key"

directions <- google_directions(origin = "St Kilda, Melbourne, Australia",
                                destination = "Geelong, Victoria, Australia",
                                key = api_key)

## the results of the API give you distance in metres, and time in seconds
## so we need to calculate teh speed
spd <- (directions$routes$legs[[1]]$steps[[1]]$distance$value / 1000) / (directions$routes$legs[[1]]$steps[[1]]$duration$value/ 60 / 60)

## then we can start to build the object to use in the plot
## and as we are staying within Google's API, we can use the encoded polyline to plot the routes
## rather than extracting the coordinates
df <- data.frame(speed = spd,
                 polyline = directions$routes$legs[[1]]$steps[[1]]$polyline)



df$floorSpeed <- floor(df$speed)
colours <- seq(1, floor(max(df$speed)))
colours <- colorRampPalette(c("red", "yellow","green"))(length(colours))

df <- merge(df, 
            data.frame(speed = 1:length(colours), 
                       colour = colours), 
            by.x = "floorSpeed", 
            by.y = "speed")

map_key <- "your_map_api_key"

google_map(key = map_key) %>%
    add_polylines(data = df, polyline = "points", stroke_colour = "colour",
                   stroke_weight = 5, stroke_opacity = 0.9)

enter image description here

有关在Shiny中制作路线规划器的方法,请参阅this answer

相关问题