![](/img/trans.png)
[英]How to crop a shapefile in such way it follows a specific latitude in a polar projection?
[英]How do I crop a shapefile to a specific set in R?
我有一個英國的shapefile,但我只想要英格蘭和威爾士。 這是我到目前為止使用的代碼:
RG <- readOGR("filepath", "filename")
UK <- grep("England", "Wales", RG$NAME_1)
RG_EW <- RG[UK]
plot(RG_EW)
但是我仍然會涉及整個英國。 我正在使用從http://www.gadm.org/下載的shapefile
謝謝
如果名稱是明確的,並且您只需要選擇兩個,那么我將只使用一種格式而不是使用grep
:
e.w.shp <- uk.shp[uk.shp$NAME_1 == "England" | uk.shp$NAME_1 == "Wales", ]
結果看起來像這樣:
> str(e.w.shp)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
..@ data :'data.frame': 134 obs. of 11 variables:
.. ..$ ID_0 : int [1:134] 239 239 239 239 239 239 239 239 239 239 ...
.. ..$ ISO : chr [1:134] "GBR" "GBR" "GBR" "GBR" ...
.. ..$ NAME_0 : chr [1:134] "United Kingdom" "United Kingdom" "United Kingdom" "United Kingdom" ...
.. ..$ ID_1 : int [1:134] 1 1 1 1 1 1 1 1 1 1 ...
.. ..$ NAME_1 : chr [1:134] "England" "England" "England" "England" ...
.. ..$ ID_2 : int [1:134] 1 2 3 4 5 6 7 8 9 10 ...
.. ..$ NAME_2 : chr [1:134] "Barking and Dagenham" "Bath and North East Somerset" "Bedfordshire" "Berkshire" ...
.. ..$ NL_NAME_2: chr [1:134] NA NA NA NA ...
.. ..$ VARNAME_2: chr [1:134] NA NA NA NA ...
.. ..$ TYPE_2 : chr [1:134] "London Borough" "Unitary Authority" "Administrative County" "County" ...
.. ..$ ENGTYPE_2: chr [1:134] "London Borough" "Unitary Authority" "Administrative County" "County" ...
..@ polygons :List of 134
因此,使用ggplot2
而不是基本圖形的完整示例可能如下所示:
library(rgdal)
library(ggplot2)
library(rgeos)
shape.dir <- "your_directory_name" # use your directory name here
uk.shp <- readOGR(shape.dir, layer = "GBR_adm2")
e.w.shp <- uk.shp[uk.shp$NAME_1 == "England" | uk.shp$NAME_1 == "Wales", ]
e.w.df <- fortify(e.w.shp, region = "ID_2") # convert to data frame for ggplot
ggplot(e.w.df, aes(x = long, y = lat, group = group)) +
geom_polygon(colour = "black", fill = "grey80", size = 0.5) +
theme()
首先,您的grep
調用不正確。 如果要查找包含“ England”或“ Wales”的字符串,則應該執行以下操作:
UK <- grep("(England|Wales)", RG$NAME_1)
然后,您可以使用以下方法對數據進行子集化:
RG_EW <- RG[UK,]
然后您最終得到:
plot(RG_EW)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.