在传单图例 R 中显示自然中断间隔

Display natural break intervals in Leaflet legend R

我尝试寻找这个问题的答案并遇到了这个问题:

但这不是我想要的,因为传单地图显示了我想要的中断,但是当我尝试使用 pal = 将它们添加到图例时,我收到错误

我已经使用 R 中的 ClassInt 包在我的数据中找到 jenks 自然中断,如下所示:

[0,3]   (3,8]  (8,16] (16,32] (32,70] 
759     505     290     138      29 

然后使用 findColours 和 RcolourBrewer 包:

cols_code <- findColours(cols_classes, brewer.pal(5,"YlGnBu"))

当我在我的传单地图中使用它时,它工作正常,并根据需要按多边形按主题显示颜色:

leaflet() %>% 
addProviderTiles("CartoDB.Positron") %>%

 addPolygons(data = foo, 
          fillColor = cols_code, 
          fillOpacity = 0.9, 
          color = "white", 
          weight = 1)

但是当我尝试使用此对象添加图例时出现错误:

addLegend(pal = cols_code, 
        values = foo$bar,
        title = "title",
        labFormat = labelFormat(suffix = " things"),
        opacity = 0.9)

Error in if (type == "numeric") { : argument is of length zero 

我尝试使用传单 colorBin 和 colorNumeric,但它们似乎无法识别我的中断,而是在图例和主题中覆盖到它们自己的间隔。

欢迎任何建议,我想尽可能避免将它们转换为因子,因为我可以看到 findColours 和 colorBin 函数都附加了调色板,但它似乎只是在传单中查找它 colorBins/numeric.

如果没有可重现的示例,就不容易知道您到底想要什么。但是尝试:

pal2 <- leaflet::colorBin(palette = col.regions,
                          bins = length(at),
                          domain = at,
                          na.color = na.color)

其中 col.regions 是生成颜色的函数(例如一些 colorRampPaletteviridis),at 是你的休息,na.color 是一些颜色对于 NA 个值。

那么你可以这样做:

leaflet::addLegend(map = m,
                   pal = pal2,
                   opacity = 1,
                   values = at,
                   title = "someTitle")

我们在 mapview 中使用它,这样我们就可以:

mapview(breweries91, zcol = "founded", 
        at = seq(1400, 2300, 300), legend = TRUE)

您显然可以使用 mapview 来为您处理。