Search code examples
rleafletlegend

Customize the legend of bubble map by using leaflet


So far I could plot the bubble map as below:

library(leaflet)
library(leafletCN)
library(plyr)

dat = data.frame(name = regionNames("china"),
                 value = 1)

data=data.frame(city=c("NJ","AH","BJ","CD","CQ"),
                 count=c(15,32,45,52,24),
                 lat=c(32,31,39,29,29),
                 long=c(118,117,116,111,106))

data2 <- data %>%
  arrange(count) %>%
  mutate(name=factor(city, unique(city))) %>%
  mutate(mytext=paste(
    "City: ", city, "\n", 
    "Population: ", count, sep="")
  )
data2

mybins <- seq(0, 60, by=10)
mypalette <- colorBin(palette="inferno", domain=data2$count, na.color="transparent", bins=mybins)

geojsonMap(dat,"china") %>%
  addCircleMarkers(data=data2,~long, ~lat, 
                   fillColor = ~mypalette(count), popup = ~mytext,
                   fillOpacity = 0.7, color="white", radius=~(count/2), stroke=FALSE)%>%
  addLegend(data=data2,pal=mypalette, values=~count, opacity=0.9, title = "Population", position = "bottomright" )

enter image description here

So how to remove the legend of Legend, and only keep the legend of Population?


Solution

  • You could use the function clearControls to remove the legend. After that you could add the legend you want like this:

    library(leaflet)
    library(leafletCN)
    library(dplyr)
    
    geojsonMap(dat,"china") %>%
      clearControls() %>%
      addCircleMarkers(data=data2,~long, ~lat, 
                       fillColor = ~mypalette(count), popup = ~mytext,
                       fillOpacity = 0.7, color="white", radius=~(count/2), stroke=FALSE)%>%
      addLegend(data=data2,pal=mypalette, values=~count, opacity=0.9, title = "Population", position = "bottomright" )
    

    Created on 2023-06-26 with reprex v2.0.2