2016-06-16 31 views
1

是否可以將鍵(例如sp.points圖層)添加到由levelplot生成的顏色鍵?將sp.points鍵添加到levelplot colorkey

看看下面的例子:

library(rasterVis) 
library(latticeExtra) 
library(sp) 

r <- as.factor(raster(matrix(rbinom(100, 1, 0.5), 10))) 
levels(r)[[1]] <- data.frame(ID=0:1, z=c('a', 'b')) 
p <- SpatialPoints(matrix(runif(20), 10)) 

levelplot(r, margin=list(draw=FALSE), scales=list(draw=FALSE), 
      col.regions=c('white', 'gray90')) + 
    latticeExtra::layer(sp.points(p, pch=20, col=1)) 

enter image description here

我想補充的一個關鍵條目點,現有的色鍵下方。

甲缺憾的解決方案是一個鍵添加到levelplot呼叫如下,調整xy值,直到它在所需的位置,但是(1)尋找合適的xy值是疼痛,需要相互作用, (2)正確的填充不會調整大小以容納該鍵,並且(3)字體大小不會自動縮放以與該顏色鍵一致。

k <- list(x = 1.02, y = 0.4, corner = c(0, 0), points=list(pch=20, col=1), 
      text=list('foo', cex=0.9)) 

levelplot(r, margin=list(draw=FALSE), scales=list(draw=FALSE), 
      col.regions=c('white', 'gray90'), key=k) + 
    latticeExtra::layer(sp.points(p, pch=20, col=1)) 

enter image description here

假設我需要堅持lattice顯卡,什麼是克服我上面列出的問題的最佳方式是什麼?

回答

1

雖然它並沒有解決您提出的所有問題,也許latticeExtra::mergedTrellisLegendGrob功能是對您有用:

p1 <- levelplot(r, scales=list(draw=FALSE), 
       col.regions=c('white', 'gray90')) 

myPoints <- SpatialPoints(matrix(runif(20), 10)) 
p2 <- spplot(myPoints, pch=20) 

## Merge graphics 
p <- p1 + p2 

## Merge legends 
l1 <- p1$legend$right 
l2 <- p2$legend$bottom 
ll <- mergedTrellisLegendGrob(l1, l2) 
p$legend$right$fun <- ll 

p 

mergedLegends

+0

感謝奧斯卡。是否可以使'p2'圖例符合levelplot鍵(即在其上方或下方,而不是旁邊)? – jbaums

+1

你應該在'mergedTrellisLegendGrob'中嘗試'vertical'參數。其默認值爲'FALSE'(如本例中)。探索它的代碼,我發現'vertical = TRUE'這個函數使用'packGrob'來把第一個圖例放在最上面,第二個圖例放在最下面。也許這不完全是你需要的。相反,您可以使用'packGrob'的'row'和'col'參數重用此函數的最後一行。 –