gpt4 book ai didi

r - 使用 R 的邻近图

转载 作者:行者123 更新时间:2023-12-04 23:14:32 25 4
gpt4 key购买 nike

我正在寻找使用 R 创建一些邻近图,它显示区域与某些点的距离。我在 R 代码中找不到任何示例,但我找到了一个我想要的输出:
enter image description here

它不一定具有所有标签/内部边界魔法,但我希望它停在海边界(考虑使用 rgeos 函数 gintersection - 参见 here )。

我试过做一个密度图作为“热图”(这将是一个很好的解决方案/替代方案)并在顶部放置一个形状文件(按照这个 suggestion ,但他们没有排队,我做不到gintersection,可能是因为密度图没有附加坐标系。enter image description here

最佳答案

我用你的问题来玩新图书馆......

获取英国 map 并定义随机点

library(raster)
library(sf)
library(ggplot2)
library(dplyr)
library(tidyr)
library(forcats)
library(purrr)

# Get UK map
GBR <- getData(name = "GADM", country = "GBR", level = 1)
GBR_sf <- st_as_sf(GBR)

# Define 3 points on the UK map
pts <- matrix(c(-0.4966766, -2.0772529, -3.8437793,
51.91829, 52.86147, 56.73899), ncol = 2)
# Project in mercator to allow buffer with distances
pts_sf <- st_sfc(st_multipoint(pts), crs = 4326) %>%
st_sf() %>%
st_transform(27700)

ggplot() +
geom_sf(data = GBR_sf) +
geom_sf(data = pts_sf, colour = "red")

Data Map

计算缓冲区

我们创建一个列表 multipolygons对于每个缓冲距离。点数据集必须在投影坐标(此处为墨卡托)中,因为缓冲区距离在坐标系的比例中。
# Define distances to buffer
dists <- seq(5000, 150000, length.out = 5)
# Create buffer areas with each distances
pts_buf <- purrr::map(dists, ~st_buffer(pts_sf, .)) %>%
do.call("rbind", .) %>%
st_cast() %>%
mutate(
distmax = dists,
dist = glue::glue("<{dists/1000} km"))
# Plot: alpha allows to see overlapping polygons
ggplot() +
geom_sf(data = GBR_sf) +
geom_sf(data = pts_buf, fill = "red",
colour = NA, alpha = 0.1)

Buffer overlap

去除重叠

缓冲区重叠。在上图中,更强烈的红色是由于透明红色的多层重叠。让我们去除重叠。我们需要从较大的区域中移除较小尺寸的缓冲区。然后我需要再次将最小的区域添加到列表中。
# Remove part of polygons overlapping smaller buffer
pts_holes <- purrr::map2(tail(1:nrow(pts_buf),-1),
head(1:nrow(pts_buf),-1),
~st_difference(pts_buf[.x,], pts_buf[.y,])) %>%
do.call("rbind", .) %>%
st_cast() %>%
select(-distmax.1, -dist.1)
# Add smallest polygon
pts_holes_tot <- pts_holes %>%
rbind(filter(pts_buf, distmax == min(dists))) %>%
arrange(distmax) %>%
mutate(dist = forcats::fct_reorder(dist, distmax))
# Plot and define color according to dist
ggplot() +
geom_sf(data = GBR_sf) +
geom_sf(data = pts_holes_tot,
aes(fill = dist),
colour = NA) +
scale_fill_brewer(direction = 2)

Buffer with holes - donut polygons

删除海中的区域

如果您只想在陆地部分找到邻近区域,我们需要删除海中的缓冲区。交点在 multipolygons 之间计算具有相同的投影。我以前实现了英国 map 的联合。
# Remove part of polygons in the sea
# Union and projection of UK map
GBR_sf_merc <- st_transform(st_union(GBR_sf), 27700)
pts_holes_uk <- st_intersection(pts_holes_tot,
GBR_sf_merc)

ggplot() +
geom_sf(data = GBR_sf) +
geom_sf(data = pts_holes_uk,
aes(fill = dist),
colour = NA) +
scale_fill_brewer(direction = 2)

这是使用 sf 的最终接近度 map , ggplot2和其他一些图书馆...

Proximity map

关于r - 使用 R 的邻近图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com