尝试过滤形状文件以简化绘图
我有从英国政府下载的形状文件:
基于此:https://www.r-bloggers.com/r-and-gis-working-with-shapefiles/
我写了但不知道要过滤:
setwd("~/Documents/filename")
getwd() # --double confirm real data directory
#install.packages("maptools")
library(maptools)
crswgs84=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
ukmap=readShapePoly("filename.shp",proj4string=crswgs84,verbose=TRUE)
class(ukmap)
str(ukmap@data)
str(ukmap@polygons[[1]])
ukmap@bbox
# <-- need to do some filterig
plot(ukmap) # as this will take too long and not want to plot whole UK
例如我只想要“E06000001”到“E06000020”。
(文件名为“Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK”,不知道如何将其包含在程序编码报价中)
答案 0 :(得分:2)
您可以考虑使用sf
包来读取shapefile并绘制数据。过滤sf
对象与过滤数据框相同。
library(sf)
# Read the sahpefile
ukmap <- st_read("Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK.shp")
# Subset the sf object
ukmap_sub <- ukmap[ukmap$lad16cd %in% c("E06000001", "E06000020"), ]
# Plot the boundary of ukmap_sub
plot(st_geometry(ukmap_sub))
如果您希望使用SpatialPolygonsDataFrame
,我们可以使用rgdal包中的readOGR
功能。之后,我们可以像常规数据框一样对SpatialPolygonsDataFrame
进行子集化。
library(maptools)
library(rgdal)
ukmap <- readOGR(dsn = getwd(), layer = "Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK")
ukmap_sub <- ukmap[ukmap$lad16cd %in% c("E06000001", "E06000020"), ]
plot(ukmap_sub)