[英]How to change labels inside a density plot to a legend on the side?
我有一個帶有幾個400MB
光柵文件的RasterStack
,我想將它們與rasterVIS
密度 function 相互比較。問題是 plot 的標簽相互重疊。 Plot 看起來與此類似...
那么是否可以將rasterVis
密度 plot 內的標簽更改為側面的圖例?
我試過類似的東西
library(raster)
library(rasterVis)
Rasterstack = stack(Rasterfile1,Rasterfile2,Rasterfile3,Rasterfile4)
labels = names(RasterStack)
densityplot(RasterStack, xlab="density", ylab="value",
auto.key= list(space="right", lines=TRUE, text=labels))
#or just#
densityplot(RasterStack, xlab="density", ylab="value", auto.key=T)
我也嘗試了這里提到的解決方案,但它對我不起作用,因為它會生成不可處理的矢量大小。 有任何想法嗎?
通過調整密度為 plot function 的 RasterVis 源代碼找到解決方案。
library(raster)
library(rasterVis)
#Adapted density plot function#
dp <- function(x, data = NULL, layers, FUN, maxpixels = 1e+05,
xlab = '', ylab = '', main = '',
par.settings = rasterTheme(), auto.key = list(columns = 4, space = "top"), ...) {
if (!missing(layers)) x <- subset(x, layers)
nl <- nlayers(x)
if (nl > 1) {
dat <- raster2dat(x, FUN, maxpixels)
p <- densityplot(~values,
data = dat, groups = ind,
breaks = 100,
par.settings = par.settings, pch = '.',
xlab = xlab, ylab = ylab, main = main, auto.key = auto.key,
panel = panel.superpose,
panel.groups = function(x, group.value, col.line, ...) {
panel.densityplot(x, col.line = col.line,
plot.points = FALSE, ...)
# d <- density(x, na.rm = TRUE)
# i <- which.max(d$y)
# ltext(d$x[i],d$y[i],
# group.value,
# adj = c(0.3,0),
# col = col.line,
# cex = 0.7)
})
} else {
p <- densityplot(x, maxpixels = maxpixels,
main = main, xlab=xlab, ylab=ylab, ...)
}
p
}
#raster2dat function from the RaserVis package#
raster2dat <- function(x, FUN, maxpixels){
nl <- nlayers(x)
if (maxpixels < ncell(x)) {
dat <- sampleRandom(x, maxpixels)
} else {
dat <- getValues(x)
}
if (nl>1){
dat <- as.data.frame(dat)
##http://r.789695.n4.nabble.com/Column-order-in-stacking-unstacking-td3349953.html
idx <- sprintf("%s%03d", "X", 1:nl)
names(dat) <- idx
dat <- stack(dat)
z <- getZ(x)
if (!missing(FUN) & !is.null(z)){
FUN <- match.fun(FUN)
dat$ind <- factor(FUN(z))[dat$ind]
} else {
nms <- names(x)
nms <- reorder(factor(nms), 1:nl)
dat$ind <- nms[dat$ind]
}
dat
} else {
dat ##nl==1 --> raster2dat gives a vector
}
}
#Test
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
s <- stack(r, r-500, r+500, r - 120)
dp(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.