如何使用Leaflet in R根据数值变量绘制带颜色的线

30byixjq  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(252)

怎么啦!
我有一个数据框,其中每一行都有一个对象的即时速度和坐标(纬度和经度)的信息。
我想画一条线,连接所有的纬度和经度,这条线的颜色代表速度,有人能帮我吗?
下面是一些代码:

require(leaflet)

df <- data.frame(Latitude = seq(14, 15, length.out = 100),
                 Longitude = seq(45, 46, length.out = 100),
                 Speed = runif(100, 50, 70))

pal <- colorNumeric(palette = "Greens", domain = df$Speed)

leaflet()%>%
    addTiles() %>%
    addPolylines(data = df,
                 lng = ~Longitude,
                 lat = ~Latitude,
                 color = ~pal(Speed))
f0brbegy

f0brbegy1#

library(leaflet)
library(tidyverse)

df <- data.frame(lat = seq(14, 15, length.out = 100), 
                 lng = seq(45, 46, length.out = 100), 
                 Speed = runif(100, 50, 70))

pal <- colorNumeric(palette = "Greens", domain = df$Speed) 

colorGradient <- df$Speed %>%
  pal

df1 <- df %>%
  mutate(nextLat = lead(lat),
         nextLng = lead(lng),
         color = colorGradient
  )

gradient_map <- leaflet() %>% 
  addTiles()

for (i in 1:nrow(df1)) {
  gradient_map <- addPolylines(map = gradient_map,
                               data = df1, 
                               lng = as.numeric(df1[i, c('lng', 'nextLng')]), 
                               lat = as.numeric(df1[i, c('lat', 'nextLat')]), 
                               color = as.character(df1[i, c('color')])
  )
}

gradient_map

Map Plot

相关问题