我是 r 的新手,也是这个网站的新手。我在当前的分发项目中遇到了一些麻烦。我的目标是创建一个具有六边形的 map ,这些六边形具有基于不同属性的颜色渐变。例如六边形中的记录数、物种数、稀疏度等。我从两个 shapefile 开始。
一个是六边形:
具有 10242 个特征和 4 个字段的简单特征集合
几何类型:多边形
维度:XY
bbox: xmin: -180 ymin: -90 xmax: 180 ymax: 90
CRS:4326
前 10 个特征:
ID CENTRELAT CENTRELON AREA geometry
1 -43.06618 41.95708 41583.14 MULTIPOLYGON (((43.50039 -4...
2 -73.41802 -144.73583 41836.20 MULTIPOLYGON (((-147.695 -7...
4862 -82.71189 -73.45815 50247.96 MULTIPOLYGON (((-78.89901 -...
7162 88.01938 53.07438 50258.17 MULTIPOLYGON (((36.63494 87...
3 -75.32015 -145.44626 50215.61 MULTIPOLYGON (((-148.815 -7...
4 -77.21239 -146.36437 50225.85 MULTIPOLYGON (((-150.2982 -...
5 -79.11698 -147.60550 50234.84 MULTIPOLYGON (((-152.3518 -...
6 -81.03039 -149.37750 50242.49 MULTIPOLYGON (((-155.3729 -...
7 -82.94618 -152.11105 50248.70 MULTIPOLYGON (((-160.2168 -...
8 -84.84996 -156.85274 50253.03 MULTIPOLYGON (((-169.0374 -...
还有一张 map :几何类型:POLYGON;维度:XY; bbox:xmin:-180 ymin:-90 xmax:180 ymax:83.64513; CRS:4326
这是来自此链接的土地形状文件: natural earth data
我用 st_read 函数加载了它们。并使用以下代码创建了一个 map :
ggplot() +
geom_sf(data = hex5) +
geom_sf(data = land) +
coord_sf(1, xlim = c(100, 180), ylim = c(0, 90))
我有一个包含物种名称、经度和纬度的数据框。大约 6300 个条目。
scientific lat lon
1 Acoetes melanonota 11.75690 124.8010
2 Acoetes melanonota 11.97500 102.7350
3 Acoetes melanonota 13.33000 100.9200
4 Acrocirrus muroranensis 42.31400 140.9670
5 Acrocirrus uchidai 43.04800 144.8560
6 Acrocirrus validus 35.30000 139.4830
7 Acutomunna minuta 29.84047 130.9178
8 Admetella longipedata 13.35830 120.5090
9 Admetella longipedata 13.60310 120.7570
10 Aega acuticauda 11.95750 124.1780
如何将这些数据分箱到 map 的六边形中并使用渐变色为它们着色?
非常感谢!
最佳答案
据我了解,您有一些点和一些多边形。你想通过它们所在的多边形来总结点的值。我做了一个可能解决方案的可重现示例:
library(sf)
library(data.table)
library(dplyr)
# Create an exagonal grid
sfc = sf::st_sfc(sf::st_polygon(list(rbind(c(0,0), c(1,0), c(1,1), c(0,0)))))
G = sf::st_make_grid(sfc, cellsize = .1, square = FALSE)
# Convert to sf object
G = sf::st_as_sf(data.table(id_hex=1:76, geom=sf::st_as_text(G)), wkt='geom')
# Create random points on the grid with random value
n=500
p = data.table(id_point=1:n,
value = rnorm(n),
x=sample(seq(0,1,0.01), n, replace=T),
y=sample(seq(0,1,0.01), n, replace=T)
)
p = p[x >= y]
P = sf::st_as_sf(p, coords=c('x', 'y'))
# Plot geometry
plot(sf::st_geometry(G))
plot(P, add=TRUE)
# Join the geometries to associate each polygon to the points it contains
# Group by and summarise
J = sf::st_join(G, P, join=sf::st_contains) %>%
dplyr::group_by(id_hex) %>%
dplyr::summarise(sum_value=sum(value, na.rm=F),
count_value=length(value),
mean_value=mean(value, na.rm=F))
plot(J)
# Plot interactive map with mapview package
mapview::mapview(J, zcol="count_value") +
mapview::mapview(P)
由 reprex package 创建于 2020-04-25 (v0.3.0)
关于r - 如何将数据分箱到 shapefile 的六边形中并绘制它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61414897/