用ggplot2绘制密度对象

时间:2014-02-14 14:39:24

标签: r plot ggplot2

我有这个对象“dens”用R“Sparr”包计算,我想用ggplot2绘制

 dens<- bivariate.density(pointcase, pilotH=diff(range(pointcase$x))/30, res = 200, edgeCorrect = TRUE) 

到目前为止,我正在密谋:

plot(dens, col = colorRampPalette(c("yellow", "red"))(14), alpha = seq(.25,.45))

我对热色或任何colorbrewer调色板不满意,我的alpha设置不受尊重。我想介绍类似于stat_density会给出的输出..

stat_density2d(aes(x = X, y = Y, fill = ..level.., alpha = ..level..),
data = data, size = 0.01,  bins = 14,  geom = "polygon", colour = "grey80")+scale_fill_gradient(low = "yellow", high = "red") +

scale_alpha(range = c(.15,.45))

是否可以解决我的设置或是否必须强化我的对象?

1 个答案:

答案 0 :(得分:0)

我设法找到了解决这个问题的方法..

require(spatstat,maptools,raster,sparr,ggplot2)

points<-structure(list(x = c(-0.111497, -0.097601, -0.097562, -0.097601, 
-0.098062, -0.097601, -0.097601, -0.097601, -0.097334, -0.094094, 
-0.093919, -0.089596, -0.094094, -0.089596, -0.093057, -0.089596, 
-0.093057, -0.093948, -0.089596, -0.089596, -0.096114, -0.073254, 
-0.073254, -0.076435, -0.076435, -0.073254, -0.073254, -0.077392, 
-0.077392, -0.073254, -0.076435, -0.077451, -0.073152, -0.08655, 
-0.08531, -0.082722, -0.077578, -0.086278, -0.086393, -0.092865
), y = c(51.518226, 51.520699, 51.518864, 51.520699, 51.517577, 
51.520699, 51.520699, 51.520699, 51.521567, 51.515606, 51.519812, 
51.518743, 51.515606, 51.518743, 51.520085, 51.518743, 51.520085, 
51.518077, 51.518743, 51.518743, 51.520747, 51.512856, 51.512856, 
51.513627, 51.513627, 51.512856, 51.512856, 51.516233, 51.516233, 
51.512856, 51.513627, 51.515523, 51.512206, 51.512651, 51.518511, 
51.518029, 51.510795, 51.509876, 51.510894, 51.510182)), .Names = c("x", 
"y"), row.names = c(NA, 40L), class = "data.frame")

extent(points)

#create owin from these extents
W <-owin(c(-0.111497,-0.073152 ), c(51.50988, 51.52157))

#Now to process the ppp object
cases<- points[,c("x","y")]
pointcase <- ppp(cases[,1], cases[,2],  window=W)  #generate the ppp  object


dens<- bivariate.density(pointcase, pilotH=diff(range(pointcase$x))/40, res = 120, edgeCorrect = TRUE) 
mydens <- data.frame(expand.grid(x = dens$X, y = dens$Y),z = as.vector(dens$Zm))

## Trying to fill-in unclosed polygons
## (maybe not the best way)
mydens[is.na(mydens$z), "z"] <- min(mydens$z, na.rm = TRUE)

## get the data for the enclosing area
bnd <- data.frame(dens$WIN$bdry[[1]][c("x", "y")])


## plotting

plon <- ggplot(mydens, aes(x = x, y = y))+theme(panel.background = element_rect(fill='white', colour='red'))
plon1<-plon+ geom_polygon(aes(z=z, fill =..level.., alpha=..level..), stat="contour", size=0.01, bins=13, color="grey60") +
# geom_path(data=bnd) +
scale_fill_gradient("level", low = "yellow", high = "red") +
scale_alpha("level", range = c(.25, .65), guide=FALSE) 

print(plon1)