我想用 0.5 度比例的栅格网格映射 x y 数据,然后计算每个 0.5 单元格内的 x y 点数

I want to map x y data with a raster grid at 0.5 degree scale, then count the number of x y points within each 0.5 cell

我有全球数据显示一个物种的预测范围作为点。我的目标是计算 0.5 度分辨率的单元格中出现的次数。

我想我可以通过在同一坐标系上创建光栅来做到这一点...

rast <- raster(xmn= -180, ymn= -90, xmx = 180, ymx = 90, resolution = 0.5,
            crs = '+proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs ')

我需要计算每个单元格中 x/y 出现的次数。

我读过的大多数示例都使用数据中的计数值,但我的数据没有计数,因为每一行都是特定于物种的。我想我需要创建某种 0.5 度的网格或网,然后用它来计算 x/y 点?

如有任何帮助,我们将不胜感激。

使用rasterize(..., fun = "count")

这是从文档 (?rasterize) 中提取的可重现示例。

library(raster)

# create a raster
r <- raster(ncols=36, nrows=18)
n <- 1000

# create some points
set.seed(123)
x <- runif(n) * 360 - 180
y <- runif(n) * 180 - 90
xy <- cbind(x, y)

# count the number of points in each raster cell
r0 <- rasterize(xy, r, fun = "count")

# visualize
plot(r0); points(xy, pch = 16, cex=0.5)


要检查 RasterLayer 的分辨率,请使用 res(raster_object)。要修改该分辨率,请使用分配:

x_res <- 100  # resolution in x
y_res <- 100  # resolution in y
res(raster_object) <- c(x_res, y_res)  # set the x,y resolution of the raster

由于您需要 0.5 度的栅格单元格,因此首先检查您的 crs 使用的是什么单位(例如 - 米),计算这些单位的 x 和 y 分辨率,然后将该分辨率分配给栅格。另请注意,纬度会根据您靠近赤道还是两极而略有不同。


要使用 ggplot 进行可视化,您可以像这样将 RasterLayer 对象转换为 data.frame。虽然我没有显示它,但您可以将这些点添加为 ggplot 对象中的另一个 geom_pointgeom_sf 层。

# convert to data.frame and plot with ggplot
df <- as.data.frame(r0, xy=TRUE)

library(ggplot2)
ggplot(df, aes(x, y, fill = layer)) +
  geom_raster() +
  scale_fill_viridis_c(na.value = "white") +
  labs(fill = "Count") +
  theme_minimal()