我写了一个函数,可以使用ggplot2添加背景并叠加前景光栅图。
编辑:我在末尾添加了更好的解决方案
它的工作原理是:我结合两个光栅图,并移动值,使值不重叠。然后,我使用包含前景色彩比例尺(例如红色->绿色)的比例尺绘制光栅层,其中背景颜色比例尺是硬编码的(黑色->白色)。颜色数量没有限制。
光栅层的图例没有显示。为了获得不包含整个比例尺的图例(这将是黑色->白色->红色->绿色),我在背景中插入了两个虚拟点。一个带有前景数据的最小值,一个带有最大值。这仅为前景数据提供了一个图例。
如果有人知道更好的缩放和创建颜色比例尺的方法,我很乐意将其添加到该功能中。
我增加了通过分位数来调整前景数据的可能性;参数fg.quant采用两个整数的向量,用于“切割”数据。
bw.scale
可以使背景栅格变暗/变亮:
bw.scale=c(0, 0.5)
表示背景图像具有从黑色到灰色(0.5)的颜色比例尺,例如。
我知道这不是一个完美的函数。但是它对我非常有用,一旦有了一些空闲时间,我将改进它并尝试消除丑陋的部分。
测试数据
r.1 <- raster(x=matrix(rowSums(expand.grid(1:10, 1:10)), nrow=10),
xmn=0, xmx=10, ymn=0, ymx=10)
r.2 <- raster(x=matrix(rnorm(16), nrow=4),
xmn=3, xmx=7, ymn=3, ymx=7)
绘图函数
BGPlot <- function(fg,
bg,
cols=c('red', 'green'),
fg.quant=c(0, 1),
bw.scale=c(0, 1),
plot.title='',
leg.name='Value') {
library(ggplot2)
fg.q <- quantile(fg, fg.quant)
fg.min <- fg.q[1]
fg.max <- fg.q[2]
fg.sc <- (fg-fg.q[1]) / (fg.q[2]-fg.q[1])
fg.sc[fg.sc<0] <- 0
fg.sc[fg.sc>1] <- 1
fg.sc <- fg.sc + 0.1
ifelse((fg.max-fg.min)/10>=1, n.dgts <- 0, n.dgts <- 1)
fg.breaks <- round(seq(fg.min, fg.max, l=5), n.dgts)
fg.breaks[1] <- ceiling(fg.min*(10^n.dgts))/(10^n.dgts)
fg.breaks[5] <- floor(fg.max*(10^n.dgts))/(10^n.dgts)
fg.labs <- paste0(c(paste0(round(fg.min, n.dgts+1), '-'),'','','',''),
fg.breaks,
c('','','','',paste0('-', round(fg.max, n.dgts+1)))
)
bg.sc <- (bg-minValue(bg)) /
(maxValue(bg)-minValue(bg)) *
(bw.scale[2]-bw.scale[1]) + bw.scale[1] -1.1
r <- merge(fg.sc, bg.sc)
r.df <- as.data.frame(rasterToPoints(r))
names(r.df) <- c('Longitude', 'Latitude', 'Value')
mid.Lon <- mean(r.df$Longitude)
mid.Lat <- mean(r.df$Latitude)
vals <-c(-1.1,-0.1, seq(0.1,1.1,l=length(cols)))
dp <-seq(fg.min,fg.max,l=length(cols))
p <-
ggplot() +
geom_point(data=data.frame(x = rep(mid.Lon, length(cols)),
y = rep(mid.Lat, length(cols)),
c = dp),
aes(x, y, color=c)) +
scale_color_gradientn(colours = cols,
breaks=fg.breaks,
labels=fg.labs,
name=leg.name) +
geom_raster(data=r.df, aes(x=Longitude, y=Latitude, fill=Value)) +
scale_fill_gradientn(colours = c('black', 'white', cols),
values = vals,
rescaler = function(x,...) x,
oob = identity,
guide = "none") +
ggtitle(label=plot.title) +
theme_light() +
labs(list(x='Lon', y='Lat')) +
theme(axis.text.y=element_text(angle=90, hjust=0.5)) +
coord_equal()
return(p)
}
函数调用
BGPlot(fg=r.2, bg=r.1, cols=c('red', 'green'), fg.quant=c(0.01, 0.99), bw.scale=c(0, 0.8), plot.title='Chlorophyll Concentration', leg.name='CHL')
![enter image description here](https://istack.dev59.com/tIItU.webp)
这是一个“真实世界”的例子:
![enter image description here](https://istack.dev59.com/1snVF.webp)
编辑:使用R软件包'RStoolbox'更好的解决方案
使用软件包RStoolbox
可以得到一个非常简单且完美工作的解决方案,函数ggR
产生灰度背景图像,函数ggRGB
产生RGB背景图像。
library(ggplot2)
library(RStoolbox)
ggR(BACKGROUND_IMAGE, geom_raster=FALSE) +
geom_raster(...)