使用布局绘制具有共同图例的栅格

时间:2017-03-14 14:54:37

标签: r layout legend raster

this问题的后续行动。我试图用一个共同的比例(图例)绘制4种不同的栅格。我已经设法做到了,但现在我想在相同的图形设备中绘制它们,在设备的右侧只显示一次刻度,并且在我放置在底部的栅格上绘制的一些元素的另一个图例该设备。

我确信这对layout()没问题,但plot.rasterlayout中的方法之间的结果为there is some incompatibility。在回答相关问题后,我使用image而非plot绘制了栅格,这似乎可以解决问题。通过这种方式,我可以使用layout()获得我的四个栅格下面的点图例。但是,现在我似乎无法找到一种方法来绘制我的 rasters 图像右侧的比例。

示例代码:

library(raster)
# generate example rasters
set.seed(123)
ras1 <- raster(ncol = 10, nrow= 10)
values(ras1) <- runif(100, 1, 10)

ras2 <- raster(ncol = 10, nrow = 10)
values(ras2) <- runif(100, 5, 50)

ras3 <- raster(ncol = 10, nrow = 10)
values(ras3) <- runif(100, 10, 100)

ras4 <- raster(ncol = 10, nrow = 10)
values(ras4) <- runif(100, 8, 80)

# stack them 
rasStack <- stack(ras1, ras2, ras3, ras4)

# obtain max and min values 
maxv <- max(maxValue(rasStack))+1
minv <- min(minValue(rasStack))

# set the breaks between min and max values
brks <- seq(minv,maxv,by=0.1)
nbrks <- length(brks)-1
r.range <- c(minv, maxv)

# generate palette
colfunc<-colorRampPalette(c("springgreen", "royalblue", "yellow", "red"))

# add up the 4 layers for the common legend
rasTot <- ras1 + ras2 + ras3 + ras4

# plot in a loop with a common legend, using legend.only = T   
par(mfrow=c(2,2))
for(i in seq_len(nlayers(rasStack))){
  tmp <- rasStack[[i]]
  plot(tmp, breaks=brks,col=colfunc(nbrks), legend = F, zlim=c(minv,maxv), 
       main = names(tmp))
  plot(rasTot, legend.only=TRUE, col=colfunc(nbrks),
       legend.width=1, legend.shrink=0.75,
       legend.args=list(text='value', side=4, font=2, line=2.5, cex=0.8))
  points(x = rnorm(5, 0, 100), y = rnorm(5, 0, 10), col = seq(1:10), pch = 16)
}

# so far so good. But when trying to add legends... 

# setting layout parameters
m <- matrix(c(1,2,6,3,4,6,5,5,5),nrow = 3,ncol = 3,byrow = TRUE)


png("example_in_png_device.png")
layout(mat = m,heights = c(0.46,0.46,0.08), widths = c(0.45, 0.45, 0.1)) 
par(mar=c(4,2,4,2))
# plotting the images
for(i in seq_len(nlayers(rasStack))){
  tmp <- rasStack[[i]]
  image(tmp, breaks=brks,col=colfunc(nbrks), zlim=c(minv,maxv), 
        main = names(tmp))
  points(x = rnorm(5, 0, 100), y = rnorm(5, 0, 10), col = seq(1:10), pch = 16)
}
# adding legend at the bottom
par(mar=c(0,2,0,2)+0.1)
plot(1, type = "n", axes = F, frame.plot = F)
legend("topleft", 
       c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"),
       fill = seq(1:10), border = "black", ncol=10,
       bg = "black", bty = "n", 
       y.intersp = 0.8, cex = 1.2)
dev.off()

所有这些都会生成如下图像:result from the previous png() call

这几乎是我想要的,所以这很好,但我无法弄清楚如何在此布局中的空格编号6中添加比例(所有4个栅格图层都是通用的)。

call to layout.show(n = 6)

任何想法都将受到高度赞赏并立即投入使用!

0 个答案:

没有答案