在 R 中绘制 GeoTIFF 栅格

问题描述

我正在尝试绘制从 here 下载的网格化人口计数 GeoTIFF 栅格。

library(raster)

#----------------------------#
# Set your working directory #
#----------------------------#

setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) # RStudio IDE preferred

getwd() # Path to your working directory

# Import the GeoTIFF file into R workspace

WorldPop <- raster("nga_ppp_2020_1km_Aggregated_UNAdj.tif")

WorldPop

#---------------------------#
# Data plotted in log-scale #
#---------------------------#

tempcol <- colorRampPalette(c("lightblue","skyblue","blue","yellow","orange","red","darkred"))

plot(log(WorldPop),main = "2020 UN-Adjusted Population Count (log-scale) \n (each grid cell is 1 km x 1 km)",col=tempcol(100),legend.width=2,legend.shrink=1,legend.args=list(text='log(Persons)',side=4,font=2,line=2.5,cex=0.8),axes=T)

#--------------------------------#
# Data plotted in absolute-scale #
#--------------------------------#

plot(WorldPop,main = "2020 UN-Adjusted Population Count (absolute-scale) \n (each grid cell is 1 km x 1 km)",legend.args=list(text='Persons',axes=T)

图 1(对数刻度)

enter image description here

图 2(绝对尺度)

enter image description here

我喜欢 Plot 1(对数刻度的数据),但 Plot 2(绝对刻度的数据)没有显示任何颜色变化。如何使绝对尺度的数据图看起来与对数尺度的数据图相似?

我愿意使用其他软件包(ggplot2 等)或其他颜色口味,只要我的情节可以区分人口稠密地区和农村地区。当我使用名为 Panoply 的不同 GIS 工具时,我最喜欢的颜色是seminf-haxby.cpt(找到 here)。看起来像这样

enter image description here

我试图在 R 中复制它,但绝对比例的图看起来不太好。在 R 中绘制 tif 栅格的任何提示或建议?

解决方法

您可以设置休息时间,如下所示:

示例数据

url <- "https://data.worldpop.org/GIS/Population/Global_2000_2020_1km_UNadj/2020/NGA/nga_ppp_2020_1km_Aggregated_UNadj.tif"
fname <- basename(url)
if (!file.exists(fname)) download.file(url,fname,mode="wb")

解决方案

library(terra)
r <- rast(fname)
plot(r,col=rev(rainbow(10,end=0.7)),breaks=c(0,10,25,50,100,250,1000,100000))

enter image description here

现在你的第二个问题(最好不要同时问两个完全不同的问题)。

下面的函数从您问题中的调色板图像中提取颜色,并且也适用于像您这样组织的其他调色板图像。

getPal <- function(f) {
    x <- rast(f)
    u <- unique(values(x))
    hex <- rgb(u[,1],u[,2],3],maxColorValue = 255)
    colorRampPalette(hex)
}

pal <- getPal("https://i.stack.imgur.com/E4d85.png")

par(mar=c(0,0))
barplot(rep(1,25),col=pal(25),space=0)

enter image description here

另一种应用中断的方法是首先使用分类。我去掉第一种颜色(白色)

x <- classify(r,c(0,100000))
plot(x,col=pal(8)[-1])

enter image description here

您可以更改标签,例如像这样

levs <- levels(x)[[1]]
levs[7] <- "> 1000"
levels(x) <- levs

要在 R 代码中使用此调色板,您可以像这样创建它(如果不想以白色开头,请删除“#FFFFFF”)

ramp <- c('#FFFFFF','#D0D8FB','#BAC5F7','#8FA1F1','#617AEC','#0027E0','#1965F0','#0C81F8','#18AFFF','#31BEFF','#43CAFF','#60E1F0','#69EBE1','#7BEBC8','#8AECAE','#ACF5A8','#CDFFA2','#DFF58D','#F0EC78','#F7D767','#FFBD56','#FFA044','#EE4F4D')
pal <- colorRampPalette(ramp)