Search code examples
rshapefilergdal

How to filter only one polygon in a map in R


I am generating a map below using a shapefile file. The map refers to a state of a specific country. Now I would like to show the map only one municipality. In this case, I would like the municipality called Ponta Grossa. I believe you have to do something like: NM_MUNICIP == PONTA GROSSA. NM_MUNICIP is an attribute of the shapefile.

> names(shp)

[1] "NM_MUNICIP" "CD_GEOCMU" 

Executable code below:

library(rgdal)

temp <- tempfile()
temp2 <- tempfile()
download.file("https://geoftp.ibge.gov.br/organizacao_do_territorio/malhas_territoriais/malhas_municipais/municipio_2015/UFs/PR/pr_municipios.zip",temp)

unzip(zipfile = temp, exdir = temp2)
shp <- readOGR(temp2)

plot(shp)

enter image description here


Solution

  • You can subset by the attribute to return only PONTA GROSSA:

    shp_subset <- shp[shp$NM_MUNICIP == "PONTA GROSSA",]
    
    plot(shp_subset)
    

    Or you can also use subset:

    subset(shp, NM_MUNICIP == "PONTA GROSSA") |>
      plot()
    

    enter image description here