Last active
January 21, 2020 22:17
-
-
Save aspina7/cf3bbfcaf98327754358de031b7e33bb to your computer and use it in GitHub Desktop.
Base-map plotting offline with {ggspatial}. Current issue is that it will only download tiles if you plot something on top, which makes it not as useful as a standalone. And the res in general. Would also be nice to be able to chuck in coords or a bbox.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Installing required packages for this template | |
required_packages <- c("here", # find your files | |
"dplyr", # clean/shape data | |
"ggplot2", # create plots and charts | |
"sf", # encode spatial vector data | |
"raster", # get and plot GADM shapefiles | |
"ggspatial") # get and plot base maps | |
for (pkg in required_packages) { | |
## install packages if not already present | |
if (!pkg %in% rownames(installed.packages())) { | |
install.packages(pkg) | |
} | |
## load packages to this current session | |
library(pkg, character.only = TRUE) | |
} | |
## retrieve province boundaries from the Global Administrative | |
## level = 1 specifies provinces | |
## must be possible to do this as sf directly no? Is available on GADM.org | |
map <- raster::getData("GADM", country = "AT", level = 1) | |
## changing GADM to a sf object | |
map <- st_as_sf(map) | |
## check the CRS | |
st_crs(map) | |
## set the CRS if not present using EPSG value | |
map <- st_set_crs(map, value = 4326) # Sets to WGS84 | |
## subset map to be just vienna | |
mapsub <- map %>% | |
filter(NAME_1 == "Wien") | |
## downloading basemap tiles | |
## This requires running the plot first to download the tiles (basemap) | |
## Or you need to tell the command where to look for the map tile in the cachedir argument (once dl'ed) | |
## plot your basemap | |
base <- ggplot() + | |
annotation_map_tile(zoom = NULL, type = "hotstyle", progress = "text", cachedir = "maps/tiles") + # osm tiles | |
geom_sf(data = mapsub, fill = NA, col = "grey50") + # shapefile as polygon | |
annotation_scale() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment