8  Shapefiles

8.1 Introduction

Shapefiles are a spatial data format originally developed by ESRI.

Shapefiles come in three major types:

  • points , to represent point features such as individual or agency locations. At larger scales, cities or towns might also be points.
  • lines━━━, to represent line features such as roads, trails, or rivers.
  • polygons ▭▯, to represent polygon features such as outlines of cities, states, or countries.

8.2 Shapefiles Are Actually Collections of Files

Shapefiles are actually a set or collection of associated files, all with the same name, and all in the same directory, but different suffixes.

R–and many other software programs–generally reference the *.shp file of the shapefile.

Show the code
list.files("./shapefiles/a2trees")
[1] "AA_Trees.cpg"     "AA_Trees.dbf"     "AA_Trees.prj"     "AA_Trees.sbn"    
[5] "AA_Trees.sbx"     "AA_Trees.shp"     "AA_Trees.shp.xml" "AA_Trees.shx"    

8.3 Call Libraries

Show the code
library(ggplot2) # beautiful graphs

library(sf) # simple (spatial) features

8.4 Open Shapefiles

Show the code
city_boundary <- read_sf("./shapefiles/AA_City_Boundary/AA_City_Boundary.shp")

buildings <- read_sf("./shapefiles/AA_Building_Footprints/AA_Building_Footprints.shp")

# trees <- read_sf("./shapefiles/a2trees/AA_Trees.shp")

# parks <- read_sf("./shapefiles/AA_Parks/AA_Parks.shp")

# university <- read_sf("./shapefiles/AA_University/AA_University.shp")

clients <- read_sf("./shapefiles/clients/clients.shp")

WashtenawRoads <- read_sf("./shapefiles/Roads/RoadCenterlines.shp")

AnnArborRoads <- st_crop(WashtenawRoads, 
                         city_boundary) # crop to only get A2 roads

# watersheds <- read_sf("./shapefiles/watersheds/Watersheds.shp")

8.5 Use ggplot to Map the Shapefiles

Show the code
ggplot(city_boundary) + # initial sf data
  # geom_sf(data = buildings,
  #         fill = "lightgrey") +
  geom_sf(data = AnnArborRoads, # first layer: Ann Arbor roads 
          color = "lightgrey") +
  geom_sf(color = "red", # second layer: city boundary
          alpha = .5) + 
  geom_sf(data = clients, # third layer: clients
          size = 1,
          color = "purple") +
  labs(title = "Demonstration of Shapefiles",
       subtitle = "Purple Clients Are Points \nGrey Roads are Lines \nRed City Boundary is Polygon") +
  theme_minimal() +
  theme(axis.text = element_text(size = rel(.5)))