rm(list=ls())
gc()
#load required packages
require(data.table)
require(here)
require(pbapply)
library(terra)
# check root directory
::here() here
Making maps in R
I recently shifted from using the raster
package for spatial data to using the incredibly versatile and fast terra
package. Since, tmap
does not provide direct integration with terra
objects, I wrote this post to show how terra
allows for plotting nice graphics using it’s inbuilt functions.
I am going to create a map of continental United States with the spatial distribution of annual \(PM2.5\) concentration for 2019. I use \(PM2.5\) concentration data from Atmospheric Composition Analysis Group (Donkelaar et al., 2021).
We begin by loading our required packages.
I use the United States Census Bureau shapefile which can be downloaded from here. I now import the shapefile.
<- terra::vect(x = here::here('data', 'shapefile', 'cb_2018_us_state_500k', 'cb_2018_us_state_500k.shp')) us.shp
I subset the shapefile by removing the states that are not part of continental United States.
<- us.shp[us.shp$NAME %in% us.shp$NAME[!us.shp$NAME %in% c("Puerto Rico", "American Samoa", "United States Virgin Islands", "Hawaii", "Guam", "Commonwealth of the Northern Mariana Islands", "Alaska")],]
us.shp <- terra::project(x = us.shp, y = 'EPSG:5070') us.shp
I now import the \(PM2.5\) concentration data for 2019.
<- terra::rast(x = here::here('data', 'pollution', 'V5GL03.HybridPM25.NorthAmerica.201901-201912.nc'),
poll.dt subds = c('GWRPM25'),
lyrs = 1L)
I now subset the \(PM2.5\) concentration raster layer for the continental United States.
<- terra::project(x = poll.dt,
poll.dt y = 'EPSG:5070')
<- terra::crop(x = poll.dt,
poll.dt y = us.shp)
<- terra::mask(x = poll.dt,
poll.dt mask = us.shp)
I now plot the map.
::plot(x = poll.dt, type = 'continuous', pax = list(labels = FALSE, tick = FALSE), maxcell = 300000000000000000) terra