gpt4 book ai didi

r - 如何在 R 中绘制多种颜色的多段线?

转载 作者:行者123 更新时间:2023-12-05 05:21:45 25 4
gpt4 key购买 nike

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

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

到目前为止,我认为您必须创建多条折线(如果我错了请纠正我)以在 route 绘制多种颜色。这就是为什么我创建了一个 for 循环,以将 PolyLine 添加到 map 中。

This is how my visualization looks like

一切如愿以偿。唯一的问题是线条的颜色。我想要线条的颜色,就像 Google 对流量所做的那样。

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

最佳答案

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

而且,当您使用 Google 的 API 获取路线时,我假设您将拥有一个 API key ,所以我将向您展示如何使用我的 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

参见 this answer在 Shiny 中制作路线规划器的方法。

关于r - 如何在 R 中绘制多种颜色的多段线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42390573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com