How to limit the number of levels generated by the density plot and?

I have some spatial data and I am using the below code to create a heatmap and extract the created levels as polygons. My question is how to limit the number of levels to create? My goal is to have, for example, 5 different density levels?

In the second step, I want to extract the polygons that belong to one specific level. Since I don't have data from the normal distribution used here in my reproducible example, there could be different polygons with the same density level.

Here is my code:

#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 can control the number of levels, and I also learned how to extract polygons with the same level. But now I am faced with the problem that some of the created areas are very small. Is there a way to control the minimum size of the area, or the number of points at least each area should contain?

+3


source to share


1 answer


To get to the first part of your question, you can add an argument bins = 5

to stat_density2d()

.



heatmap <- ggplot(data,aes(x=lon,y=lat))+  stat_density2d(data=data,
                  aes(x=lon, y=lat, fill=..level.., alpha=..level..),
                  bins = 5, geom="polygon")

      

+3


source







All Articles