0

I am working with the R programming language.

I am following this tutorial here (https://cengel.github.io/R-spatial/mapping.html) and trying to make a "heatmap" like this:

enter image description here

Here is the code I am using:

# input shapefile = sf
st_trans = st_transform(sf, 4326)

breaks_qt <- classIntervals(sf$my_variable, n=7, style = "quantile")
pal_fun <- colorQuantile("YlOrRd", NULL, n=7)


m = leaflet(st_trans) %>%
    addPolygons(
        stroke = FALSE,
        fillColor = ~pal_fun(my_variable),
        fillOpacity = 0.8, smoothFactor = 0.5,
        popup = label_text) %>%
    addTiles(group = "OSM") %>%
    addProviderTiles("CartoDB.DarkMatter",group = "Carto") %>%
    addLegend("bottomright", 
              colors = brewer.pal(7, "YlOrRd"),
              labels = paste0("up to ", format(breaks_qt$brks[-1], digits = 2)),
              title = 'Legend Title') %>%
    addLayersControl(baseGroups = c("OSM", "Carto"),
    overlayGroups = c("groups"))

In the past, this above code has worked well - however, this time, "my_variable" (e.g. number of Spelling Bee champions in each polygon) has many zeros which I think is causing problems in the labels = paste0("up to ", format(breaks_qt$brks[-1], digits = 2)) and classIntervals(sf$my_variable, n=7, style = "quantile") lines (e.g. Error: 'breaks' are not unique')

I tried looking at previous posts (e.g. Cut() error - 'breaks' are not unique) and was able to use one of the answers here to resolve the first problem, e.g.

a_ranks <- rank(st_trans$my_variable, ties.method = "first")
st_trans$my_variable <- cut(a_ranks, quantile(a_ranks, probs=c(0, 0.15, 0.30, 0.45, 0.60, 0.75, 0.90)), include.lowest=TRUE, labels=FALSE)  

m = leaflet(st_trans) %>%
    addPolygons(
        stroke = FALSE,
        fillColor = ~pal_fun(my_variable),
        fillOpacity = 0.8, smoothFactor = 0.5,
        popup = label_text) %>%
    addTiles(group = "OSM") %>%
    addProviderTiles("CartoDB.DarkMatter",group = "Carto") %>%
    addLegend("bottomright", 
              colors = brewer.pal(7, "YlOrRd"),
              labels = paste0("up to ", format(st_trans$my_variable, digits = 2)),
              title = 'Legend Title') %>%
    addLayersControl(baseGroups = c("OSM", "Carto"),
    overlayGroups = c("groups"))

But I still get an error: Error in addLegend(),: 'colors' and 'labels' must be of the same length

In general, are there any methods I can use to avoid these problems?

Thanks!

Note: I can get the map to work without the legend

leaflet(st_trans) %>%
        addPolygons(
            stroke = FALSE,
            fillColor = ~pal_fun(my_variable),
            fillOpacity = 0.8, smoothFactor = 0.5,
            popup = label_text) %>%
        addTiles(group = "OSM") %>%
        addProviderTiles("CartoDB.DarkMatter",group = "Carto")
stats_noob
  • 5,401
  • 4
  • 27
  • 83

0 Answers0