I am trying to add shapefiles
on top of a ggmap
object. Specifically, I would like to use Simple Feature
(SF) shapefiles
downloaded from the R
package Tigris
. I have tried to overlay these on Stamen
and Google Maps from ggmap
.
Packages used:
library(tigris)
library(tidyverse)
library(ggmap)
library(sf)
First download shapefiles
from the Tigris
package. I am using county shapes for the states of Texas. I am specifically downloading these as an SF object (opposed to an SP object).
shp_tx <- tigris::counties(cb = TRUE,
resolution = "20m",
year = 2018,
class = 'sf',
state = 'TX')
I then calculate a bounding box from this object, which is used to download a stamen ggmap
.
my_bbox <- sf::st_bbox(shp_tx) %>% as.numeric()
my_map <- ggmap::get_stamenmap(bbox = my_bbox,
maptype = 'toner-lite',
zoom = 5)
Now when I try to overlay the counties shapefile
on the ggmap
, the borders do not properly align.
ggmap(my_map) +
geom_sf(data = shp_tx,
aes(geometry = geometry),
col = 'blue',
fill = 'lightblue',
alpha = 0.25,
inherit.aes = FALSE)
My understanding is that I need to re-project the shp_tx
(SF) object into a CRS
to match the my_map (ggmap
) object.
I have tried multiple projections based on online posts, but none seem to work appropriately. Here are the ones I have tried:
shp_tx2 <- sf::st_transform(shp_tx,
crs = 3857)
ggmap(my_map) +
geom_sf(data = shp_tx2,
aes(geometry = geometry),
col = 'blue',
fill = 'lightblue',
alpha = 0.25,
inherit.aes = FALSE)
And
shp_tx3 <- sf::st_transform(shp_tx,
crs = 4326)
ggmap(my_map) +
geom_sf(data = shp_tx2,
aes(geometry = geometry),
col = 'blue',
fill = 'lightblue',
alpha = 0.25,
inherit.aes = FALSE)
I'm not sure if this transformation would be the same using a Stamen Map
or a Google Map, but I have tried both and have had similar problems. I'm hoping the solution is as simple as transforming to correct CRS. Thanks.