Skip to content

Instantly share code, notes, and snippets.

@BobTheScientist
Created May 3, 2016 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BobTheScientist/2ea0e0258d98380337524a633039385e to your computer and use it in GitHub Desktop.
Save BobTheScientist/2ea0e0258d98380337524a633039385e to your computer and use it in GitHub Desktop.
R Function to create a circle size legend in Leaflet
# Function to create a circle size legend in Leaflet
# This takes as input a variable to determine the size range,
# a number of sizes to show, and a label and writes the HTML
# to create the legend.
#
# It requires some custom CSS that must be included somewhere:
#
# .legendCircle {
# border-radius:50%;
# border: 2px solid black;
# display: inline-block;
# position: relative;
# }
#
# There is no guarantee that the sizes will be comparable, so
# use with caution. This assumes you are mapping circle radius
# to the square root of the value. If some other function is
# being used, if should be changed in the fuction.
circleSizeLegend <- function(x,n,label) {
# Get the range
max.x = max(x)
min.x = min(x)
# Set up the initial header for the code
# The width is set to be reasonable and make the spacing work.
# It really should be done more intelligently.
myhtml <- paste0("<div id='customlegend' style='width:90px'><strong>",label,"</strong><br>")
# Loop over the number of divisions
myvalue = round(max.x, 0)
size = round(sqrt(myvalue) * 2, 1)
margin = 16 # This is just a good starting value visually
for(i in 1:n){
myhtml <- paste0(myhtml,"<div class = 'legendCircle' style='width: ",size,"px;height: ",
size,"px; margin-left:",margin,"px'></div><span style='position:absolute;right:8px'>",
myvalue,"</span><br>")
if (i == n){break}
# Compute value for next iteration
myvalue = round(max.x - (i * ((max.x - min.x) / (n - 1))),0)
oldsize = size
size = round(sqrt(myvalue) * 2, 1)
margin = margin + (oldsize - size) / 2
}
# Close up the div
myhtml <- paste0(myhtml,"</div>")
return(myhtml)
}
@guilhermeparreira
Copy link

Could you put an example of how to use your function?

I have this function:

leaflet(dat2) %>% # Apenas cria o objeto leaflet
  addProviderTiles(provider = providers$Esri.WorldStreetMap) %>% #Apenas incorpora o tema
  addPolygons(data = sp.reg
              ,weight = 2) %>% 
    addCircleMarkers(radius = ~(Atendimentos)/4,
                   stroke = F,
                   fillOpacity = 0.65,
                   weight = 1,
                   label = labels2)

and I want to add a legend (My attempts did not synchronize the legend with the CircleMarkers).
Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment