如果您在问题中包含一些数据,这真的很有帮助,即使(尤其是)它是一个玩具数据集。你不知道,我做了一个玩具例子。首先,我定义了一个简单的形状数据框和一个包含x、y 和grp 的合成数据数据框(即一个具有5 个级别的分类变量)。我将后者裁剪为前者并绘制结果,
# Dummy shape function
df_shape <- data.frame(x = c(0, 0.5, 1, 0.5, 0),
y = c(0, 0.2, 1, 0.8, 0))
# Load library
library(ggplot2)
library(sgeostat) # For in.polygon function
# Data frame of synthetic data: random [x, y] and category (grp)
df_synth <- data.frame(x = runif(500),
y = runif(500),
grp = factor(sample(1:5, 500, replace = TRUE)))
# Remove points outside polygon
df_synth <- df_synth[in.polygon(df_synth$x, df_synth$y, df_shape$x, df_shape$y), ]
# Plot shape and synthetic data
g <- ggplot(df_shape, aes(x = x, y = y)) + geom_path(colour = "#FF3300", size = 1.5)
g <- g + ggthemes::theme_clean()
g <- g + geom_point(data = df_synth, aes(x = x, y = y, colour = grp))
g
接下来,我创建一个规则网格并使用多边形对其进行裁剪。
# Create a grid
df_grid <- expand.grid(x = seq(0, 1, length.out = 50),
y = seq(0, 1, length.out = 50))
# Check if grid points are in polygon
df_grid <- df_grid[in.polygon(df_grid$x, df_grid$y, df_shape$x, df_shape$y), ]
# Plot shape and show points are inside
g <- ggplot(df_shape, aes(x = x, y = y)) + geom_path(colour = "#FF3300", size = 1.5)
g <- g + ggthemes::theme_clean()
g <- g + geom_point(data = df_grid, aes(x = x, y = y))
g
要按合成数据集中最近的点对该网格上的每个点进行分类,我使用knn 或 k = 1 的 k-nearest-neighbours。这给出了类似的结果。
# Classify grid points according to synthetic data set using k-nearest neighbour
df_grid$grp <- class::knn(df_synth[, 1:2], df_grid, df_synth[, 3])
# Show categorised points
g <- ggplot()
g <- g + ggthemes::theme_clean()
g <- g + geom_point(data = df_grid, aes(x = x, y = y, colour = grp))
g
所以,这就是我将如何解决您关于在网格上对点进行分类的那部分问题。
您问题的另一部分似乎与解决方案有关。如果我理解正确,即使您放大了,您也需要相同的分辨率。此外,您不想在缩小时绘制这么多点,因为您甚至看不到它们。在这里,我创建了一个绘图函数,可让您指定分辨率。首先,我绘制形状中的所有点,每个方向有 50 个点。然后,我绘制了一个子区域(即缩放),但在每个方向上保持相同数量的点相同,这样就点数而言,它看起来与上一个图几乎相同。
res_plot <- function(xlim, xn, ylim, yn, df_data, df_sh){
# Create a grid
df_gr <- expand.grid(x = seq(xlim[1], xlim[2], length.out = xn),
y = seq(ylim[1], ylim[2], length.out = yn))
# Check if grid points are in polygon
df_gr <- df_gr[in.polygon(df_gr$x, df_gr$y, df_sh$x, df_sh$y), ]
# Classify grid points according to synthetic data set using k-nearest neighbour
df_gr$grp <- class::knn(df_data[, 1:2], df_gr, df_data[, 3])
g <- ggplot()
g <- g + ggthemes::theme_clean()
g <- g + geom_point(data = df_gr, aes(x = x, y = y, colour = grp))
g <- g + xlim(xlim) + ylim(ylim)
g
}
# Example plot
res_plot(c(0, 1), 50, c(0, 1), 50, df_synth, df_shape)
# Same resolution, but different limits
res_plot(c(0.25, 0.75), 50, c(0, 1), 50, df_synth, df_shape)
由reprex package (v0.3.0) 于 2019 年 5 月 31 日创建
希望这能解决您的问题。