This chapter explores mapping of point patterns:
Under the course folder, please create a folder called “lab7”. Next, in the lab7 folder, please create two sub-folders that one is called “data” and another one is “plot”.
This chapter uses:
Download the lab’s data:
If there you have any questions about the above-mentioned steps, please refer to Chapter 3.2.3 for detailed instructions.
Again, we would like to start a new project from scratch with a clean R Script. Please do the following steps. If you have any questions about these steps, please refer to the relevant chapters for help.
Please install necessary packages as needed.
library(dplyr) ## mutate, left_join
library(sf) ## simple feature manipulation and processing
library(tmap) ## mapping
library(spatstat) ## kernel density map
Simple Features (sf) - spatial data
# Colorado: county subdivision (cartographic boundary)
sf_co_cousub <- st_read("data/cb_2023_us_cousub/cb_2023_us_cousub_500k.shp") %>%
filter(STATE_NAME == "Colorado")
# crash data
sf_crash <- st_read("data/crash_data/cos_crash_2024.shp")
# road data
sf_road <- st_read("data/tl_2023_08041_roads/tl_2023_08041_roads.shp")
Check the coordinate reference system of “sf_co_cousub” - county
subdivisions. sf_co_cousub is in a Geodetic Coordinate
Reference System “NAD83”.
# check coordinate reference systems
sf_co_cousub$geometry
## Geometry set for 209 features
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -109.0603 ymin: 36.99243 xmax: -102.0415 ymax: 41.00344
## Geodetic CRS: NAD83
## First 5 geometries:
the following line project the Geodetic CRS to a planar CRS “NAD83 / Colorado North (ftUS)”. CRS code: 2231
# project to CRS NAD83 / Colorado North (ftUS)
sf_co_cousub <- st_transform(sf_co_cousub, 2231)
Filter county subdivision based on county & city names
# el paso county: county subdivision
sf_ep_cousub <- sf_co_cousub %>% filter(NAMELSADCO == "El Paso County")
# olorado springs
sf_cos_cousub <- sf_ep_cousub %>% filter(NAME == "Colorado Springs")
Examine the crash data.
# top 5 rows
head(sf_crash, 5)
# data type
str(sf_crash)
The crash data has some records with empty geometry, e.g., row 10. Let’s have a look at an example ‘empty point’ in the 10th row.
sf_crash[10, ]$geometry
Data filtering: We can use the function st_is_empty() identifies empty geometry.
sf_crash[st_is_empty(sf_crash),]
The logical NOT operator ! can be used to reverse the condition to extract NON-EMPTY geometry
# extract records with non-empty geometry
sf_crash_24 <- sf_crash[!st_is_empty(sf_crash),]
# project to CRS NAD83 / Colorado North (ftUS)
sf_crash_24 <- st_transform(sf_crash_24, 2231)
Visualization: quick interactive map.
# set tmap mode for interactive mapping
tmap_mode("view")
# plot crash data and cos county subdivision
tm_shape(sf_cos_cousub) + tm_polygons(fill_alpha = 0, lwd = 3, col = "blue") +
tm_shape(sf_crash_24) + tm_dots(fill_alpha = 0.5)