作者:徐大总统_584 | 来源:互联网 | 2023-05-18 12:10
IhavesomespatialdataandIusethecodebelowtocreateaheatmapandtoextractthecreatedlev
I have some spatial data and I use the code below to create a heatmap and to extract the created levels as polygons. My question is now how to limit the number of levels which are created? My goal is to have e.g. 5 different density levels?
我有一些空间数据,我使用下面的代码创建一个heatmap并将创建的级别提取为多边形。我的问题是如何限制创建的级别的数量?我的目标是有5个不同的密度?
In a second step I want to extract the polygons which belong to one specific level. Since I do not have data from a normal distribution as used here in my reproducible example, there might be different polygons with the same density level.
在第二步中,我想提取属于一个特定级别的多边形。由于我没有正态分布的数据,在我的可再现的例子中,可能有不同的多边形具有相同的密度水平。
Here is my code up to now:
下面是我的代码:
#Load packages
library(ggplot2)
library(sp)
#create spatial data
lon<-rnorm(10000,mean = 15,sd=1)
lat<-rnorm(10000,mean=45,sd=1)
data <-cbind.data.frame(lon,lat)
#create the heatmap
heatmap <- ggplot(data,aes(x=lon,y=lat))+ stat_density2d(data=data,
aes(x=lon, y=lat, fill=..level..,
alpha=..level..), geom="polygon")
# build the heatmap without plotting it
gb_heat <- ggplot_build(heatmap)
# extract the polygon specifications
gb_heat_dat <- gb_heat$data[[1]]
# make some polygons!
SpatialPolygons(lapply(unique(gb_heat_dat$group), function(x) {
pts <- gb_heat_dat[gb_heat_dat$group == x,]
Polygons(list(Polygon(as.matrix(data.frame(x=pts$x, y=pts$y)))), as.character(x))
})) -> polys
# plot them
plot(polys)
Edit: Thanks to @pHroc's answer I am able to control the number of levels and I also found out how to extract the polygons with the same level. But now I encountered the problem that some created areas are very small ones. Is there a way to control the minimum size of an area or the number of points each and every area should at least contain?
编辑:感谢@pHroc的回答,我能够控制级别的数量,我还发现了如何提取具有相同级别的多边形。但是现在我遇到了一个问题,有些创建的区域很小。是否有一种方法来控制一个区域的最小大小或每个区域至少应该包含的点的数量?
1 个解决方案