Home > database >  Legend using leaflet
Legend using leaflet

Time:05-04

I create this code, it is work but when I add a legend it doesn't work well. Someone can help me? I need the legend has the same value of nycounties$dimension, also I need to reorder increase.

    nycounties <- rgdal::readOGR("https://raw.githubusercontent.com/openpolis/geojson-italy/master/geojson/limits_IT_provinces.geojson")

city <- c("Novara", "Milano","Torino","Bari")
dimension <- as.numeric(c("1500", "5000","3000","4600"))
df <- data.frame(city, dimension)

nycounties@data = data.frame(nycounties@data,
                             df[match(nycounties@data[, "prov_name"],
                                      df[, "city"]),])
pal <- colorNumeric("viridis", NULL)

nycounties$dimension[is.na(nycounties$dimension)] = 0

leaflet(nycounties) %>%
  addTiles() %>%
  addPolygons(stroke = TRUE, smoothFactor = 0.3, fillOpacity = 1,
              fillColor = ~pal(nycounties$dimension), weight = 1, color = "black", label = nycounties$prov_name) %>%
  addLegend(pal = pal, values = ~(nycounties$dimension), opacity = 1.0,
            labFormat = labelFormat(unique(nycounties$dimension)))

CodePudding user response:

You can delete labFormat = labelFormat(unique(nycounties$dimension)) and switch to values = ~unique(dimension) because you are referring to the wrong data (in nycountries but it needs to be in nycounties@data).

Therefor:

leaflet(nycounties) %>%
  addTiles() %>%
  addPolygons(stroke = TRUE, smoothFactor = 0.3, fillOpacity = 1,
              fillColor = ~pal(nycounties$dimension), weight = 1, color = "black", label = nycounties$prov_name) %>%
  addLegend(pal = pal, 
            values = ~unique(dimension), 
            opacity = 1.0)

Output is:

enter image description here

  • Related