Search code examples
rdictionaryleafletlabel

Vary label color in R Leaflet


I have a data frame with a binary variable and xy coordinates. I can map the data with Leaflet and vary the color of the markers for each variable, but I want to know if I can also vary the label color.

Below is an example of the data. Right now I can only make the labels one color (e.g., black). In this example, I'd like labels for electronics to be blue font and labels for non-electronics to be red font.

library(leaflet)
library(mapview)

data <- data.frame("ID"=1:5, "Name" = c("ipod", "book", "phone", "ipod", "book"), "Color" = c("blue","red","blue","blue","red"), "Lat"=c(38.56250,38.66163,38.66574,38.55060,38.55060), "Long"=c(-90.59690,-90.5000,-90.37138,-90.35756,-90.5285))

pal<-(colorFactor(c("blue","red"), domain=c("blue", "red")))

map <-leaflet()  %>% addTiles() %>% 
  setView(lng = -90.576959, lat  = 38.440455, zoom = 10) %>% 
  addProviderTiles("Esri") %>%
  addCircleMarkers(data=data, lng = ~Long, lat= ~Lat, radius = 5, fillColor = ~pal(`Color`), color="black", fillOpacity = .90, weight = 1) %>%
  addLabelOnlyMarkers(
    data = data,
    label = as.character(data$Name),
    labelOptions = labelOptions(noHide = T, #hides labels
                                direction = "auto", 
                                textOnly = F, 
                                offset = c(0,0),
                                style = list(
                                  "color" = "black", 
                                  "font-family" = "serif",
                                  "font-style" = "normal",
                                  "box-shadow" = "1px 1px rgba(0,0,0,0.25)",
                                  "font-size" = "12px",
                                  "border-color" = "rgba(0,0,0,0.5)",
                                  "padding" = "2px" 
                                )))
map

Solution

  • You need to do a little workaround by replacing the label with HTML.

    In addLabelOnlyMarkers() function, replace label = as.character(data$Name) with following codes:

    label = purrr::map(glue::glue("<span style='color:{data$Color}'>{as.character(data$Name)}<span>"),htmltools::HTML)
    

    So instead of using text as labels, you are using HTML as labels:

    [[1]]
    <span style='color:blue'>ipod<span>
    
    [[2]]
    <span style='color:red'>book<span>
    
    [[3]]
    <span style='color:blue'>phone<span>
    
    [[4]]
    <span style='color:blue'>ipod<span>
    
    [[5]]
    <span style='color:red'>book<span>
    

    enter image description here