使用传单的图例

Legend using leaflet

我创建了这段代码,它可以工作,但是当我添加一个图例时它不能正常工作。有人可以帮助我吗?我需要图例具有与 nycounties$dimension 相同的值,还需要重新排序增加。

    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)))

您可以删除 labFormat = labelFormat(unique(nycounties$dimension)) 并切换到 values = ~unique(dimension),因为您指的是错误的数据(在 nycountries 中,但它需要在 nycounties@data 中)。

因此:

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)

输出为: