Skip to content

Instantly share code, notes, and snippets.

@jebyrnes
Last active August 8, 2022 14:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jebyrnes/349f513c902590f20945 to your computer and use it in GitHub Desktop.
Save jebyrnes/349f513c902590f20945 to your computer and use it in GitHub Desktop.
Basic leaflet mapping in R
#Load the library and make a basic map
library(leaflet)
leaflet() %>% addTiles()
#Show a map with a satellite picture on it
leaflet() %>%
addTiles(urlTemplate="http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}")
#Make a demo fake data set
set.seed(100)
myData <- data.frame(Latitude = runif(100, -80,80),
Longitude = runif(100, -180,180),
measurement1 = rnorm(100, -3, 2),
Year = round(runif(100, 1975,2015)))
#Plot sites on an interactive map
leaflet() %>%
addTiles() %>%
addCircles(data=myData, lat = ~Latitude, lng = ~Longitude)
#Make a label for the next map
myData$info <- paste0("Year: ", myData$Year,
"<br> Value: ", round(myData$measurement1, 3))
#make some colors!
#colors
#grab a palette
library(RColorBrewer)
pal <- brewer.pal(11, "Spectral")
#now make it more continuous
#as a colorRamp
pal <- colorRampPalette(pal)
#now, map it to your values
library(classInt)
palData <- classIntervals(myData$measurement1, style="quantile")
#note, we use pal(100) for a smooth palette here
#but you can play with this
myData$colors <- findColours(palData, pal(100))
#Put it all on a map!
leaflet() %>%
addTiles() %>%
addCircles(data=myData, lat = ~Latitude, lng = ~Longitude,
color = ~colors, popup = ~info)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment