我正在尝试映射一个变量 uisng GGplot,但图层不匹配,有没有办法可以解决这个问题,以便它们匹配?
ggplot() +
geom_sf(data = sf_data) +
geom_point(data=point_data,aes(x, y))
我有地图,但点不匹配。
鉴于在示例代码中使用了
geom_point()
,此表示假定您的 point_data 对象是一个数据帧。这是实现您想要的工作流程:
st_intersection()
仅返回那些落在 sf_data 多边形范围内的点请注意,运行此代码时您将收到一条警告,您可以安全地忽略该警告。它只是意味着数据的CRS是地理坐标系而不是投影坐标系。根据您实际数据的 CRS,您可能会也可能不会收到警告。
加载需求包并创建示例数据
library(sf)
library(dplyr)
library(ggplot2)
# Example polygon sf data
sf_data <- st_read(system.file("shape/nc.shp", package = "sf"))
# Example points df
point_data <- st_make_grid(sf_data, cellsize = 0.5) %>%
st_as_sf() %>%
st_cast("POINT") %>%
rename(geometry = "x") %>%
mutate(x = st_coordinates(.)[,1],
y = st_coordinates(.)[,2]) %>%
st_drop_geometry()
head(point_data)
# x y
# 1 -84.32385 33.88199
# 2 -83.82385 33.88199
# 3 -83.82385 34.38199
# 4 -84.32385 34.38199
# 5 -84.32385 33.88199
# 6 -83.82385 33.88199
将point_data转换为point sf对象,分配CRS,使其与sf_data的CRS匹配,子集数据
# Convert point_data dataframe to point sf object and assign CRS from sf_data
sf_points <- st_as_sf(point_data, coords = c("x", "y"), crs = st_crs(sf_data))
# Subset points using sf_data as the st_intersection() object
sf_points1 <- st_intersection(sf_points, sf_data)
ggplot() +
geom_sf(data = sf_data, colour = "grey75") +
geom_sf(data = sf_points, aes(colour = "All Points")) +
geom_sf(data = sf_points1, aes(colour = "Subset points")) +
theme(panel.background = element_blank())