R贴图 - 在地图中绘制点时过滤坐标

时间:2015-02-23 11:41:54

标签: r maps coordinates

我有一个大型数据框的事件位置(经度,纬度)。请参阅以下示例:

events <- structure(list(lat = c(45.464944, 40.559207, 45.956775, 44.782831, 45.810287, 35.913357, 43.423855, 45.2359, 45.526025, 41.91371, 46.340833, 40.696482, 42.367164, 41.913701, 41.89167, 46.046206, 41.108316, 45.514132, 45.688118, 37.090387, 43.446555, 41.913712, 46.614833, 45.368825, 41.892168), lon = c(9.163453, 8.321587, 12.983347, 10.886471, 9.077844, 10.560439, 6.768272, 9.23176, 9.375761, 12.466994, 6.889444, 17.316925, 13.352248, 12.466992, 12.516713, 14.497758, 16.871019, 12.056176, 9.176543, 15.293506, 6.77119, 12.466993, 15.194904, 11.110711, 12.516085)), .Names = c("lat", "lon"), row.names = c(NA, 25L), class = "data.frame")

我想仅绘制某个国家(例如意大利)发生的事件。

以下绘制了所有事件:

library(rworldmap)
library(maps)
par(mar=c(0,0,0,0))
plot(getMap(resolution="low"), xlim = c(14,14), ylim = c(36.8,47))
points(x=events$lon, y=events$lat, pch = 19, col ='red' , cex = 0.6)

如何过滤掉国家/地区范围之外的事件?提前感谢您的帮助和支持。

1 个答案:

答案 0 :(得分:3)

将多边形贴图指定给对象:

m = getMap(resolution="low")

将事件转换为sp对象 - 第一个经度,然后是纬度:

pts = SpatialPoints(events[c(2,1)])

指定CRS:

proj4string(pts) = proj4string(m)

在任何多边形内绘制点:

points(pts[m,], pch = 3)

在意大利境内选择点:

it = m[m$ISO_A2 == "IT",]
points(pts[it,], col = 'blue')

(这使用sp::over,但在幕后)