I'm trying to create a leaflet map with points sized by a variable. Is it possible to create a legend with different sized circles representing the different variable values? I found another post showing how to convert squares to circles in the legend, but am not sure how to change the size of different circles in the legend.
For example, here's a dummy script which creates 10 points associated with 2 classes of a variable (5 and 10). I'd like a legend with two circles the same size as that specified with addCircleMarkers with a radius of 5 and 10. If anyone can modify to create what I want I would be extremely grateful! Thanks!
library(shiny)
library(leaflet)
#create data
Points<-data.frame(x=runif(10,20,21), y=runif(10,0,1), var=rep(c(5,10),5))
map = leaflet() %>% addTiles()
# Set up shiny app
shinyApp(ui=bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}",
".leaflet .legend i{
border-radius: 50%;
width: 10px;
height: 10px;
margin-top: 4px;
}
"
),
leafletOutput("myMap", width = "100%", height = "100%")),
server= function(input, output){
output$myMap = renderLeaflet({map %>%
addCircleMarkers(Points$x,Points$y,radius=Points$var) %>%
addLegend(colors=rep("blue",2), labels=c(5,10))
})
})
You're in luck. A closer look at the
leaflet.js
shows that the configurations your add inside theaddLegend
command, are used literally to create the legend items:This way, we can sneak in some extra styling. Within the
colors
arguement, we add somewidth
andheight
to change the size of thei
tag (= the legend circle). And (this is optional) we can make thelabels
adiv
with modified alignment style, because they tend to be stuck way to the top of the line, if the circle gets big.I took the liberty to create a custom legend function for you. This takes an additional value for the circle sizes. (It's a very minimal function for just this one application.) It then adds the styling I mentioned above without you needing to worry about typos or other errors. Note that the standard size is 10.
Code below. Have fun! And please write if there are any mistakes or bugs. I could not test for every possible scenario.