我有一个带有二进制变量和 xy 坐标的数据框。我可以使用 Leaflet 映射数据并改变每个变量的标记颜色,但我想知道是否也可以改变标签颜色。
以下是数据示例。现在我只能将标签设置为一种颜色(例如黑色)。在此示例中,我希望电子产品的标签为蓝色字体,非电子产品的标签为红色字体。
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
您需要做一些解决方法,将标签替换为 HTML。
在
addLabelOnlyMarkers()
函数中,将 label = as.character(data$Name)
替换为以下代码:
label = purrr::map(glue::glue("<span style='color:{data$Color}'>{as.character(data$Name)}<span>"),htmltools::HTML)
因此,您不再使用文本作为标签,而是使用 HTML 作为标签:
[[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>