聚合每个网格单元格的统计信息并绘制 R 中的热图

aggregate statistics on each cell of grid and plot heatmap in R

以下是伦敦的自行车租赁数据。每个点代表一个循环租用点。

我使用 st_make_grid() 创建了一个网格。现在我想 -

  1. 绘制网格每个单元格中循环租用点数量的热图

  2. 绘制网格每个单元格中 nbike 总数的热图 (nbikes - 当前停放的自行车数量)

library(spData)
library(sf)

# cycle hire data of london
# Each observaion represent a cycle hire point in London.
hire_sf <- spData::cycle_hire

head(hire_sf)

# create grid
grid_area <- st_make_grid(hire_sf)

# 1. plot heatmap of number of cycle hire point in each cell

# 2. plot heatmap of total nbikes in each cell
# (nbikes - The number of bikes currently parked)

这确实是重复的;但我们不妨提供一个可能的解决方案。所以考虑下面的代码:

它建立在 sf::st_join() 的基础上,它在空间上连接两个 sf 对象(在本例中为网格和点),同时保留数据属性。

请注意,默认情况下连接是左侧的(在 SQL 中),因此所有行(网格单元格)都保留在第一个对象中。没有雇用的单元格将有 NA,多个点的重复行(因此请务必提前为每个单元格分配一个唯一的 ID,以便于聚合)。

join 中第一个对象的类型决定了生成的几何类型,所以如果你想以多边形类型结果结束,请务必从网格开始/从点开始你会得到点结果。

一旦将点分配给网格单元,它就是一个聚合练习 - 我建议通过 {dplyr} 技术,但基础 R 也可以。

对于最终的热图,您可能需要 ggplot 来完善结果,但基本图可以用于概念验证。

library(spData)
library(sf)
library(dplyr)

# cycle hire data of london
# Each observaion represent a cycle hire point in London.
hire_sf <- spData::cycle_hire

head(hire_sf)

# create grid
grid_area <- st_make_grid(hire_sf) %>% 
  st_as_sf() %>% 
  mutate(grid_id = 1:n())

# join data to grid; make sure to join points to grid
# the first object drives the output geometry
result <- grid_area %>%
  st_join(hire_sf) %>% 
  group_by(grid_id) %>% 
  summarise(point_count = n(),
            total_bikes = sum(nbikes))

# draw heatmap
plot(result["point_count"])