rstudio / leaflet

R Interface to Leaflet Maps
http://rstudio.github.io/leaflet/
Other
805 stars 509 forks source link

Adding labels to polylines increases line opacity #922

Open rbechtel-MITRE opened 3 months ago

rbechtel-MITRE commented 3 months ago

Adding labels or popups to polylines increase the line's opacity. The increase in opacity seems to be related to the number of points used to plot the polyline as if each time a label is added the opacity bumps up. It seems you can account for this by decreasing the opacity proportional to the number of points that makeup the polyline.

library(leaflet)

data <- tibble(x = c(10,20,30,40), y = c(10,20,30,40), label = rep("label",4))

#has default opacity
m <- leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolylines(data = data, lng = ~x, lat = ~y)

#has opacity closer to 1
m <- leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolylines(data = data, lng = ~x, lat = ~y, label = ~label)

#decreases opacity 
m <- leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolylines(data = data, lng = ~x, lat = ~y,# label = ~label,
               opacity = 0.5 / nrow(data), fill = 0.2 / nrow(data)) #default values divided by rows in data
jack-davison commented 2 months ago

I think this is because leaflet recycles the label four times - this works fine:

leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolylines(
    data = data,
    lng = ~ x,
    lat = ~ y,
    label = ~ label[1]
  )

Or see this version, where you can toggle between the different labels.

data <- tibble(x = c(10,20,30,40), y = c(10,20,30,40), label = paste0("label", 1:4))

#has default opacity
leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolylines(data = data, lng = ~x, lat = ~y, label = ~label, group = ~label) %>%
  addLayersControl(baseGroups = data$label)

If you want different labels per segment, you could do something like:

data <-
  tibble(
    x = c(10, 20, 30, 40),
    y = c(10, 20, 30, 40),
    label = paste0("label", 1:4),
    color = c("red", "blue", "green", "orange")
  )

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

for (i in seq_along(data$label)) {
  if (i > 1) {
    m <- 
      addPolylines(
        map = m,
        lng = data$x[(i-1):i],
        lat = data$y[(i-1):i],
        label = data$label[i],
        color = data$color[i]
      )
  }
}

print(m)
rbechtel-MITRE commented 2 months ago

Yep, adding [1] resolves the issue for me.