簡體   English   中英

R [raster]:如何使用柵格圖層來確定另一個圖層的透明度?

[英]R [raster] : How to use a raster layer to determine transparency of another layer?

讓我們假設我有兩個柵格層,一個是給定區域中給定物種的估計豐度之一,另一個是估計值的一定程度的不確定性。 為了簡單起見,我使用了一個非常簡單的例子,產生了下面的兩張圖(左:豐富,右:不確定)。

library(raster)
par(mfrow = c(1,2))
par(mar = c(5.1, 4.1, 4.1, 5.1))
abund <- matrix(1:16, 4)
abund.r <- raster(abund)
plot(abund.r, col = colorRampPalette(c("red", "blue"), space = "rgb")(16))
uncert <- matrix(c(rep(0.2, 8), rep(0.8, 8)), 4, byrow = TRUE)
uncert.r <- raster(uncert)    
plot(uncert.r)

給定代碼的示例映射

在這個例子中,該地區北部的估計不如南部的估計。 我正在尋找在一張地圖中結合豐富和不確定性的可能性。 我想通過使用與左圖中相同的顏色來顯示不確定性,並根據右圖中的不確定性值修改網格中每個單元的透明度。 因此,北部的豐度估計應該比南部的估計更加透明(不太確定)(更確定)。 但是,alpha參數只接受單個值,例如:

plot(MAT1.r, col = colorRampPalette(c("red", "blue"), space = "rgb")(16),
     alpha = 0.5)

當我嘗試使用矢量時,只使用它的第一個元素。

我的問題:如何使用不確定性圖中的信息來修改豐度圖中的透明度? 我們非常感謝任何有關替代方法的解決方案或建議的暗示。

每當你想通過數據可視化進行額外的努力時, ggplot2都是非常有資源的。 考慮一下:

library(raster)
library(ggplot2)

abund.r <- raster(matrix(1:16, 4))
uncert.r <- raster(matrix(c(rep(0.2, 8), rep(0.8, 8)), 4, byrow=T))

#Layer the two rasters into one multi-band raster for easier manipulation
abu_unc <- stack(abund.r, uncert.r)

#Get cell positions in cartesian coordinates for each cell
coords <- xyFromCell(object=abu_unc, cell=1:ncell(abu_unc))

#abu_unc is a 2 layer raster where band 1==abundance and band 2==uncertainty
#Convert abu_unc () to a dataframe
abu_unc_df <- as.data.frame(abu_unc)

#Add cell coordinates 
dat <- data.frame(coords, abu_unc_df)
colnames(dat) <- c("x", "y","Abundance", "Uncertainty")

#Plot dat, where the fill is abundance and transparency (alpha), is the respective uncertainty value
mymap <- ggplot(data=dat) + theme_bw() + coord_equal() +
 geom_raster(aes(x=x, y=y, fill=Abundance, alpha=Uncertainty)) +

  scale_alpha_continuous(range=c(0.4, 1), breaks=seq(0.4, 1, 0.1))+
  scale_fill_gradient2(mid="yellow", high = "darkgreen")+
  scale_x_continuous(expand=c(0.01,0.01)) + 
  scale_y_continuous(expand=c(0.01,0.01)) +

  #General aesthetics
  theme(
    axis.title.x = element_text(size=12),
    axis.title.y = element_text(size=12, angle=90),
    axis.text = element_text(size=10),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank()
  )
    print(mymap)

#Save plot to file
    ggsave(filename = "mymap.png", plot= mymap, dpi=300)

注意用法:

  • scale_fill_gradient2()來自定義豐度填充
  • scale_alpha_continous()用於不確定性透明度

你可以擺弄這兩個,讓圖形看起來像你認為最適合你的數據。

在此輸入圖像描述

使用當前版本的“raster”,您可以使用矢量或RasterLayer來設置透明度(alpha)

library(raster)
abund.r <- raster(matrix(1:16, 4))
uncert.r <- raster(matrix(c(rep(0.2, 8), rep(0.8, 8)), 4, byrow = TRUE))    

plot(abund.r, col=colorRampPalette(c("red", "blue"), space="rgb")(16), alpha=uncert.r)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM