rlabellegendr-leaflet

Create Custom Labels in Leaflet Legend


Map Image

I have created a map in leaflet. The legend is currently numbered 0, 2, 4, 6, 8. However, I would instead like just two labels. One saying 'Less Dense' and another saying 'More Dense'.

I am currently using a shape file merged to a column for the logged population density of each country.

Thanks in advance for your help.

My map looks like so, in the attached image.

Here is the code I currently use to create the map

library(here) #create wkd
library(utils) #unzip file
library(rgdal) #read the shape file
library(dplyr) #clean the data
library(leaflet) #creates interactive graph
library(RColorBrewer) #modifies colour pallette with custom bins
library(viridis) #allows for additional colour pallettes

# Create a color palette for the map:

# Call the color function (colorBin) to create a new palette function. Domain allows the colouring of continuous data

mypalettepop <- colorNumeric( palette="Purples", domain=worldCountries@data$pop_density_log)

# Pass the palette function a data vector to get the corresponding colors
mypalettepop(c(45,43))

#create a highlight
highlight <- highlightOptions(
  weight = 2,
  color = "white",
  fillOpacity = 1.0,
  opacity = 1.0,
  bringToFront = TRUE)

labels_pop <- c("Less Dense", "", "", "", "More Dense") # added labels to over ride the 5 previous labels

# Final Map
pop_map <- leaflet(worldCountries) %>% 
  addTiles()  %>% 
  setView( lat=10, lng=0 , zoom=2) %>%
  addPolygons( 
    fillColor = ~mypalettepop(pop_density_log), 
    stroke=TRUE, 
    fillOpacity = 0.9, 
    color="white", 
    weight=0.7,
    label = mytext,
    labelOptions = label,
    highlightOptions = highlight  
  )%>% 
  addLegend( 
    pal=mypalettepop, 
    values=~pop_density_log, 
    opacity=0.9, 
    title = "Population Density per KM2", 
    position = "bottomleft",
    labels = labels_pop #added labels but still will not change
  ) 

pop_map

Solution

  • The labels argument are a vector of text labels in the legend corresponding to colors argument rather than pal argument within addLegend()

    library(rgdal)
    
    # From http://data.okfn.org/data/datasets/geo-boundaries-world-110m
    countries <- readOGR("https://rstudio.github.io/leaflet/json/countries.geojson")
    map <- leaflet(countries) %>% addTiles()
    pal <- colorNumeric(
      palette = "YlGnBu",
      domain = countries$gdp_md_est
    )
    map %>%
      addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
                  color = ~pal(gdp_md_est)
      ) %>%
      addLegend("bottomright", colors = c('red', 'orange', 'yellow', 'green', 'blue'), values = ~gdp_md_est,
                title = "Est. GDP (2010)",
                labels = c("Less Dense", "", "", "", "More Dense"),
                opacity = 1
      )
    

    This example uses sample data, because I could not access your data

    sample