7 Mapping with leaflet
7.1 Overview
leaflet is an R package for building interactive maps. It is especially useful when your data include locations, coordinates, regions, or boundaries and you want viewers to explore the map directly.
leaflet(data = ...) %>%
addTiles() %>%
add*()-
data: dataset
-
leaflet(): initializes the map
-
addTiles(): adds a basemap
-
add*(): adds markers, circles, polygons, or other layers
-
%>%: builds the map step by step
7.2 Basic Map
7.3 Add a Single Marker
leaflet() %>%
addTiles() %>%
addMarkers(
lng = -96.7970,
lat = 32.7767,
popup = "Dallas, Texas"
)7.4 Map Data from a Dataset
leaflet(quakes) %>%
addTiles() %>%
addMarkers(
lng = ~long,
lat = ~lat
)7.5 Markers vs Circle Markers
NoteKey Distinction
-
addMarkers()places standard map pins -
addCircleMarkers()draws scalable points on the map
For most data visualization tasks, addCircleMarkers() is preferred.
leaflet(quakes) %>%
addTiles() %>%
addCircleMarkers(
lng = ~long,
lat = ~lat
)7.6 Encode Size with Magnitude
NoteKey Idea
Marker size is one of the most effective ways to encode magnitude in a map.
leaflet(quakes) %>%
addTiles() %>%
addCircleMarkers(
lng = ~long,
lat = ~lat,
radius = ~mag
)7.6.1 Scaling Marker Size
Raw values are often too small or too large. Scale them for readability:
leaflet(quakes) %>%
addTiles() %>%
addCircleMarkers(
lng = ~long,
lat = ~lat,
radius = ~mag * 2, # simple scaling
fillOpacity = 0.7
)You can also normalize:
7.7 Add Rich Popups and Labels
7.8 Use Color Intentionally
TipColor Best Practices
- Use color to encode a meaningful variable
- Ensure contrast with the basemap
- Avoid too many categories
pal <- colorNumeric(
palette = "viridis",
domain = quakes$mag
)
leaflet(quakes) %>%
addTiles() %>%
addCircleMarkers(
lng = ~long,
lat = ~lat,
radius = ~mag * 2,
color = ~pal(mag),
fillOpacity = 0.7
)7.9 Add a Legend
7.10 Adjust the View
7.11 Change the Basemap
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron)7.12 Interactivity
NoteWhy Use
leaflet?
Users can: - zoom and pan - click for details - explore spatial patterns
7.13 Workflow
TipRecommended Approach
- Start with a basemap
- Add points
- Encode magnitude with size
- Add color and labels
- Refine view and legend
7.14 Summary
- Use
radiusto encode magnitude
- Scale size for readability
- Combine size + color for clarity
- Use popups to avoid clutter
7.15 Exercise
leaflet(quakes) %>%
addTiles() %>%
addCircleMarkers(
lng = ~long,
lat = ~lat
)Modify: - Scale radius by mag - Add color by mag - Add a popup