0
votes

I can't seem to find any way to make the leaflet path a gradient based on another variable. For a given dataframe using lat/lng pairs from below:

df <- data.frame(lat = lat, lng = lng, var = c(1:25))

So the leaflet plot should look like:

leaflet() %>% 
addTiles() %>% 
      addPolylines(data = df, lng = ~lng, lat = ~lat, 
                   color = ~var)

But this will just color the whole path the same color.

Even if I do:

pal <- colorNumeric(
  palette = "Blues",
  domain = df$var)

leaflet() %>% 
    addTiles() %>% 
          addPolylines(data = df, lng = ~lng, lat = ~lat, 
                       color = ~pal(var))

This doesn't work either.


Reproducible Example:

df <- data.frame(lat = rnorm(40) * 2 + 13, 
                 lng = rnorm(40) + 48, 
                 var = c(1:40))

pal <- colorNumeric(
  palette = "Blues",
  domain = df$var)

leaflet() %>% 
  addTiles() %>% 
  addPolylines(data = df, lng = ~lng, lat = ~lat, 
               color = ~pal(var))

All same color lines

1
What are you expecting the result to be - each of the 40 segments are different colours, or, each segment has a gradient fill?SymbolixAU
I guess more like the former, each segment has a different color. But really I'm thinking as in ggplot2 where you can color a path dependent on another continuous variable. So it becomes a gradient color along the path.conv3d
You will need to create a separate 'line' for each segment, similar to the approach in this question and answer. You can then colour each segment/line separately.SymbolixAU

1 Answers

0
votes

Somewhat late to the party, but as SymbolixAU wrote, you'll need a separate Polyline for each row in the dataset. Full example below:

library(leaflet)
library(dplyr)
library(grDevices)

set.seed(1234)
df <- data.frame(lat = rnorm(40) * 2 + 13, 
                 lng = rnorm(40) + 48, 
                 var = c(1:40))

gradientFunction <- colorRampPalette(c("white", "blue"))
colorGradient <- gradientFunction(dim(df)[1])

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

Screenshot