如何在R中绘制形状文件之前对其进行过滤 [英] How to filter a shape file before plotting it in R
问题描述
只是尝试过滤形状文件以简化绘图
Just to try to filter a shape file to ease plotting
我有一个从UK gov下载的形状文件:
I have a shape file downloaded from UK gov:
基于此: https://www. r-bloggers.com/r-and-gis-working-with-shapefiles/
我写了,但不知道要过滤:
I wrote but do not know to filter :
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".
For example I just want "E06000001" to "E06000020".
(文件名是"Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK",不确定如何将其包含在程序编码引号中)
(the filename is "Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK" not sure how to include it in the program coding quote)
推荐答案
您可以考虑使用sf
包读取shapefile并绘制数据.过滤sf
对象与过滤数据帧相同.
You can consider to use the sf
package to read the shapefile and plot the data. Filtering the sf
object is the same as filtering a data frame.
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 软件包.之后,我们可以像常规数据帧一样对SpatialPolygonsDataFrame
进行子集化.
If you prefer to work with on SpatialPolygonsDataFrame
, we can use the readOGR
function from the rgdal package. After that, we can subset the SpatialPolygonsDataFrame
like a regular data frame.
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)
这篇关于如何在R中绘制形状文件之前对其进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!