如何裁剪位于多边形内的数据点并绘图
Posted
技术标签:
【中文标题】如何裁剪位于多边形内的数据点并绘图【英文标题】:How can I crop the data points which lie inside polygon and plot 【发布时间】:2022-01-10 19:20:47 【问题描述】:如何裁剪位于给定多边形内的数据点?
library(tidyverse)
tbl <- tibble(x = runif(100),
y = runif(100))
ggplot(data = tbl,
aes(x = x,
y = y)) +
geom_point() +
theme_bw() +
coord_equal()
poly <- tibble(A = c(0.5, 0),
B = c(1, 0.5),
C = c(0.5, 1),
D = c(0, 0.5))
【问题讨论】:
非常相关的***.com/q/50144222/7941188 【参考方案1】:一种方法是将点和多边形转换为sf
对象,裁剪点,然后将数据转换回小标题。
library(sf)
library(tidyverse)
library(gridExtra)
set.seed(345)
tbl <- tibble(x = runif(100),
y = runif(100))
poly <- tibble(
A = c(0.5, 0),
B = c(1, 0.5),
C = c(0.5, 1),
D = c(0, 0.5)
)
# Convert tbl to sf object.
tbl_sf <- sf::st_as_sf(tbl, coords = c("x", "y"))
# Convert polygon to sf polygon.
poly_sf <- as.data.frame(t(poly)) %>%
dplyr::rename(x = V1, y = V2) %>%
sf::st_as_sf(coords = c("x", "y")) %>%
dplyr::summarise() %>%
sf::st_cast("POLYGON") %>%
sf::st_convex_hull()
# Keep only points inside the polygon.
points <- sf::st_intersection(tbl_sf, poly_sf) %>%
# Get coordinates and convert back to tibble.
sf::st_coordinates() %>%
as_tibble() %>%
dplyr::rename(x = X, y = Y)
before <- ggplot(data = tbl,
aes(x = x,
y = y)) +
geom_point() +
theme_bw() +
coord_equal() +
ggtitle("Before")
after <- ggplot(data = points,
aes(x = x,
y = y)) +
geom_point() +
theme_bw() +
coord_equal() +
ggtitle("After")
grid.arrange(before, after, ncol = 2)
输出
【讨论】:
以上是关于如何裁剪位于多边形内的数据点并绘图的主要内容,如果未能解决你的问题,请参考以下文章