R -如何用sf包制作距离图?

2skhul33  于 2023-04-27  发布在  其他
关注(0)|答案(3)|浏览(132)

下面是一个例子:

library(sf)
library(tidyverse)

nc <- st_read(system.file("shape/nc.shp", package="sf")) %>% 
  st_union()

centroid <- st_centroid(nc)

ggplot(nc) +
  geom_sf() +
  geom_sf(data = centroid)

现在我想创建一个距离图,显示该区域距离质心有多远。我正在寻找this here link上从底部数第三张图像的样式。
我如何创建Map?谢谢。

b91juud3

b91juud31#

你可以创建一个距离栅格,需要首先转换到投影CRS,相关的ggplot图层来自tidyterraEPSG:6542恰好是公制,所以你可能想选择其他东西或只是转换单位。

library(sf)
library(terra)
library(tidyterra)
library(ggplot2)

# transform to projected CRS for distance calculation, units are meters
# NAD83(2011) / North Carolina (EPSG:6542) 
nc <- st_read(system.file("shape/nc.shp", package="sf")) |>
  st_union() |>
  st_transform(nc, crs = 6542)

centroid <- st_centroid(nc)

nc_spatvect <- vect(nc)
c_spatvect  <- vect(centroid)
dist_rast <- distance(rast(nc_spatvect, resolution = 1000 ),c_spatvect) |> mask(nc_spatvect)

# meters to km
dist_rast <- dist_rast / 1000

ggplot(nc) +
  geom_spatraster(data = dist_rast, aes(fill = lyr.1)) +
  scale_fill_viridis_c(na.value = NA, option = "plasma", direction = -1, labels = scales::label_number(suffix = "km")) +
  geom_sf(fill = NA) +
  geom_sf(data = centroid) +
  theme_bw()

或者,如果你只需要一个简单的距离图,可以删除sfggplot2tidyterra

nc_spatvect <- vect(system.file("shape/nc.shp", package="sf")) |> 
  aggregate() |> 
  project("epsg:6542")

c_spatvect <- centroids(nc_spatvect)

distance(rast(nc_spatvect, resolution = 1000), c_spatvect) |>
  mask(nc_spatvect) |> 
  plot(col = viridis::plasma(100, direction = -1))
plot(c_spatvect, add = TRUE)

创建于2023-04-24带有reprex v2.0.2

iszxjhcz

iszxjhcz2#

您可以使用terra制作区域的栅格,查找像元距离,并使用ggplot2tidyterra绘制它们。

library(sf)
library(terra)
library(tidyverse)
library(tidyterra)

nc <- st_read(system.file("shape/nc.shp", package="sf")) %>%
  st_union() %>% st_as_sf()

centroid <- st_centroid(nc)

# Use terra::rast to make a 50x50 grid,
#  terra::distance for the distance from cells to centroid,
#  terra::mask to get only the cells inside nc
nc_rast <- rast(nc, nrows = 50, ncols = 50)

nc_dist <- distance(nc_rast, centroid)                                     

nc_dist_masked <- mask(nc_dist, nc)

# plot
# direction = -1 makes 'yellow' the color for closer cells
ggplot() +
  geom_sf(data = nc) +
  geom_spatraster(data = nc_dist_masked) +
  geom_sf(data = centroid, color = 'red') +
  scale_fill_viridis_c(option = 'C', direction = -1)

# or without ggplot2
plot(nc_dist_masked)
plot(centroid, add = T)

reprex package(v2.0.1)于2023-04-24创建

b4lqfgs4

b4lqfgs43#

下面是如何使用terra和base-plot来实现这一点

library(terra)
nc <- vect(system.file("shape/nc.shp", package="sf")) |> 
  aggregate()

centroid <- centroids(nc)
r <- rast(nc, res=.01)
d <- distance(r, centroid, unit="km") |> mask(nc)

plot(d, buffer=TRUE); points(centroid); lines(nc)

相关问题