2

I have some spatial data points and I want to cluster them. Therefore I use the heatmap function of ggplot2. I get a nice looking heat map but I wan't to do some further analysis with the created areas and to be able to do this I want to extract the created polygons.

How can I do this? Or do I have to use another heatmap function and if so which one shall I use then?

I tried to produce a reproducible example. Here it is:

library(ggplot2) 

lon<-rnorm(10000,mean = 15,sd=1)
lat<-rnorm(10000,mean=45,sd=1)
data <-cbind.data.frame(lon,lat)

heatmap <- ggplot(data,aes(x=lon,y=lat))+  stat_density2d(data=data,
                   aes(x=lon, y=lat,  fill=..level..,
                     alpha=..level..), geom="polygon")
heatmap
user2988757
  • 105
  • 1
  • 1
  • 8
  • 5
    you can get your density data with `ggplot_build(heatmap)[[1]][[1]]`. If you provide a reproducible example, a more thorough answer could be provided. – Rorschach Aug 03 '15 at 15:32
  • @nongkrong I don't know how to create a data frame with random points to create a reproducible example. In my code "data" is just a data frame with 2 columns lon and lat and some values. – user2988757 Aug 03 '15 at 16:04
  • 2
    see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for ideas – Rorschach Aug 03 '15 at 16:11

1 Answers1

3

Once you build out the plot, it's just a matter of making the polygons:

library(ggplot2)
library(MASS)
library(sp)

# get some data
data(geyser)

# mimic your plot
m <- ggplot(geyser, aes(x = duration, y = waiting)) + xlim(0.5, 6) + ylim(40, 110)
hm <- m + stat_density2d(aes(fill = ..level..), geom="polygon")

# build the plot w/o plotting it
gb <- ggplot_build(hm)

# take a look
str(gb$data)

# this is what we want
dat <- gb$data[[1]]

# make some polygons!
SpatialPolygons(lapply(unique(dat$group), function(x) {
  pts <- dat[dat$group == x,]
  Polygons(list(Polygon(as.matrix(data.frame(x=pts$x, y=pts$y)))), as.character(x))
})) -> polys

# make a SPDF (add more data to it if you need to)
polys_dat <- SpatialPolygonsDataFrame(polys, 
                                      data.frame(id=sapply(slot(polys, "polygons"), slot, "ID"),
                                                 row.names=sapply(slot(polys, "polygons"), slot, "ID"),
                                                 stringsAsFactors=FALSE))

# plot them!
plot(polys, asp=1/20)

enter image description here

# plot level 5
plot(polys_dat[polys_dat$id=="1-005",], asp=1/20)

enter image description here

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • This is exactly what I was looking for. Is there also a possibility now to control the number of levels created, e.g. 5 levely only? – user2988757 Aug 04 '15 at 06:50
  • No I don't want to extract one level, I want to control how many levels will be created. Shall I post it as a separate question? – user2988757 Aug 04 '15 at 14:33