如何将标签放在传单的调色板中而不是数值

How put labels in the palette of leaflet instead of numeric values

这是 Shiny 文档中的示例。

df <- data.frame(x = rnorm(100), y = rexp(100, 2), z = runif(100))
pal <- colorBin("PuOr", df$z, bins = c(0, .1, .4, .9, 1))
leaflet(df) %>%
  addTiles() %>%
  addCircleMarkers(~x, ~y, color = ~pal(z), group = "circles") %>%
  addLegend(pal = pal, values = ~z, group = "circles", position = "bottomleft") %>%
  addLayersControl(overlayGroups = c("circles"))

我想在调色板中显示:

level1, 
level2, 
level3, 
level4 

而不是

0-0.1
0.1-0.4
0.4-0.9
0.9-1

我将参数 labels=("level1", "level2", "level3", "level4") 添加到 addLegend

df <- data.frame(x = rnorm(100), y = rexp(100, 2), z = runif(100))
pal <- colorBin("PuOr", df$z, bins = c(0, .1, .4, .9, 1))
leaflet(df) %>%
  addTiles() %>%
  addCircleMarkers(~x, ~y, color = ~pal(z), group = "circles") %>%
  addLegend(pal = pal, values = ~z, group = "circles", position = "bottomleft",
            labels = c("A","B","C","D")) %>%
  addLayersControl(overlayGroups = c("circles"))

但没有任何改变。

您需要 labFormat 参数,而不是标签。在 ?addLegend 你有一个解释。 这如你所愿:

library(leaflet)
  df <- data.frame(x = rnorm(100), y = rexp(100, 2), z = runif(100))
  pal <- colorBin("PuOr", df$z, bins = c(0, .1, .4, .9, 1))
  
  labeller_function <- function(type, breaks) {
    return(c('A', 'B', 'C', 'D'))
  }
  
  leaflet(df) %>%
    addTiles() %>%
    addCircleMarkers(~x, ~y, color = ~pal(z), group = "circles") %>%
    addLegend(pal = pal, values = ~z, group = "circles", position = "bottomleft",
              labFormat = labeller_function) %>%
    addLayersControl(overlayGroups = c("circles"))