Cassidy
Cassidy

Reputation: 423

How to crop a multipolygon shapefile?

I'm trying to figure out how to crop a multipolygon shapefile. Most of the tutorials and other stack overflow responses have shown just polygons. I'm tired of following tutorial after tutorial and getting nowhere with my shapefile. Here is my current code. I'm reading in the urban/rural 2020 census database.

practice <- st_read(
  "tl_rd22_us_uac20.shp")

st_geometry_type(practice)
st_crs(practice)

library(ggplot2)

# Set the new latitude and longitude limits
latitude_limits <- c(40, 45)
longitude_limits <- c(72, 80)

practice_cropped <- st_crop(practice, c(xmin= 40, ymin = 72, xmax = 45, ymax = 80))



ggplot() + 
  geom_sf(data = practice, size = 1.5, color = "black", fill = "cyan1") + 
  coord_sf()

Here is where the shapefile is located: https://www2.census.gov/geo/tiger/TIGER_RD18/LAYER/UAC20/

When I plot the shapefile, this is what I get: enter image description here

The cropping code is what doesn't want to work for me. I get this error: Warning message: attribute variables are assumed to be spatially constant throughout all geometries

Please help this poor graduate student.

Upvotes: 0

Views: 201

Answers (1)

Till
Till

Reputation: 6663

library(sf)
library(ggplot2)

practice <- st_read("tl_rd22_us_uac20.shp")

Turn off spherical geometry, to make operations faster and avoid possible errors when cropping.

sf_use_s2(FALSE)
#> Spherical geometry (s2) switched off

Crop: Adjust values to your liking.

practice_cropped <-
  st_crop(
    practice,
    xmin = -130,
    ymin = 0,
    xmax = -50,
    ymax = 180
  )
#> although coordinates are longitude/latitude, st_intersection assumes that they
#> are planar
#> Warning: attribute variables are assumed to be spatially constant throughout
#> all geometries

ggplot() +
  geom_sf(
    data = practice_cropped,
    size = 1.5,
    color = "black",
    fill = "cyan1"
  ) +
  coord_sf()

Upvotes: 2

Related Questions