library(tidyverse)
library(sf)
library(tidygeocoder)
library(maps)
Static Maps w/ ggplot
Libraries
tidygeocoder
Let’s find the latitude and longitude for a couple of places.
<- tibble(address=c("Smith College", "2 Tyler Ct, Northampton, MA 01060", "Holyoke Community College")) |>
addressesgeocode(address, method="osm") |>
mutate(name = c("Smith College","McConnell Hall","Holyoke Community College"))
addresses
# A tibble: 3 × 4
address lat long name
<chr> <dbl> <dbl> <chr>
1 Smith College 42.3 -72.6 Smith College
2 2 Tyler Ct, Northampton, MA 01060 42.3 -72.6 McConnell Hall
3 Holyoke Community College 42.2 -72.7 Holyoke Community College
My first map
Let’s plot those with ggplot.
ggplot(addresses) +
geom_point(aes(long,lat))
Not very exciting. We’ll add it it in a moment.
Mass Map data
Let’s build a map of Massachusetts with the map_data() function
# map_data comes from ggplot2
<- map_data("county", "massachusetts") |>
ma_counties select( long, lat, group, id = subregion)
head(ma_counties)
long lat group id
1 -70.67435 41.73997 1 barnstable
2 -70.53683 41.79727 1 barnstable
3 -70.53683 41.79727 1 barnstable
4 -70.51392 41.78008 1 barnstable
5 -70.47954 41.75716 1 barnstable
6 -70.41078 41.73425 1 barnstable
Mass Map
Notice there are a lot of points for barnstable. Those are the vertices of a polygon. Let’s draw the polygon with the points.
|> ggplot(aes(long,lat,group=group))+
ma_counties geom_polygon(fill = "white", colour = "grey50")+
geom_point()
#coord_sf()
Mapping projections
Coordinate Reference Systems (CRS) - Is the type of map projection employed To get a 3D Earth to a 2D surface.
Which one will coord_sf default to?
?coord_sf
West wing explanation
Adding the 4326 crs
|> ggplot(aes(long,lat,group=group))+
ma_counties geom_polygon(fill = "white", colour = "grey50")+
geom_point()+
coord_sf()
Add some cities
Let’s grab just Massachusetts cities from the data frame us.cities.
# us.cities comes from the maps package
<- us.cities |>
ma_cities filter(country.etc =="MA") |>
select(name, long, lat)
head(ma_cities)
name long lat
1 Andover MA -71.14 42.65
2 Arlington MA -71.16 42.42
3 Attleboro MA -71.30 41.93
4 Barnstable Town MA -70.30 41.70
5 Beverly MA -70.84 42.56
6 Billerica MA -71.26 42.56
Exercise:
Plot MA cities onto our county map. Then clean up our map.
|> ggplot(aes(long,lat))+
ma_counties geom_polygon(fill = "white", colour = "grey50",aes(group=group)) +
#geom_point(data=ma_cities,.......)
#This is the default mapping. Think GPS
coord_sf(default_crs= st_crs(4326) )
# This is Mercator
# st_crs(3857))
Shape files
Often times map data is saved as a shape file.
The US government has shape files here.