我有以下代码。它绘制了美国的地图。对于这些点,我正在使用一个名为“ x $ osm_points”的对象,但是其中一些点不在美国多边形范围内。我想删除这些内容,只显示美国境内的点。有办法吗?
x $ osm_points看起来像这样
Simple feature collection with 1249248 features and 0 fields
geometry type: POINT
dimension: XY
bbox: xmin: -125.9051 ymin: 24.39989 xmax: -65.243 ymax: 49.38759
CRS: EPSG:4326
First 10 features:
geometry
1 POINT (-80.29432 43.38873)
2 POINT (-80.29536 43.38858)
3 POINT (-80.2953 43.3884)
4 POINT (-80.29515 43.38829)
5 POINT (-80.29497 43.3882)
6 POINT (-80.29481 43.38813)
7 POINT (-80.29458 43.38805)
8 POINT (-80.29436 43.38806)
9 POINT (-80.29415 43.38806)
10 POINT (-80.29402 43.38809)
ggplot代码如下:
ggplot() +
geom_polygon(data = map_data("usa"), aes(x=long, y = lat, group = group), fill = "black", color = "black", alpha = 1) +
geom_sf(data = x$osm_points,
inherit.aes = FALSE,
colour = "cyan4",
#fill = "#004529",
alpha = .1,
size = 0.5)
谢谢
您可以只将美国数据创建为空间sf对象,然后使用st_intersection
裁剪点。
usa <- st_as_sf(map_data('usa'), coords=c('long', 'lat'), crs=4326) %>%
st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326) %>%
group_by(group) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POLYGON") %>%
st_union()
clipped_points <- st_intersection(x$osm_points, usa)
ggplot() +
geom_polygon(data = map_data("usa"), aes(x=long, y = lat, group = group), fill = "black", color = "black", alpha = 1) +
geom_sf(data = clipped_points,
inherit.aes = FALSE,
colour = "cyan4",
#fill = "#004529",
alpha = .1,
size = 0.5)
编辑将x更改为x $ osm_points。 map_data返回剪裁之前必须转换为多边形sf文件的纬度长的多边形坐标。