跨栅格砖/堆栈的各个层绘制的更好方法

时间:2018-10-01 12:32:39

标签: r ggplot2 dplyr raster sp

我正在尝试在栅格砖中为特定点绘制所有值。这是为特定像素的遥感数据创建光谱图。

我可以通过多种方式来执行此操作,但是它们笨拙且缓慢(请参见下面的示例)。这很慢,主要是因为将大型栅格文件转换为矩阵会占用大量内存。

是否有更好的方法可以使用baseR或整洁的韵律和内置的方法在一个光栅/遥感软件包中执行此操作?

这是一个可重复的示例:

library (raster)
library (rgdal)
library (sp)
library (tidyr)
library (ggplot2)
library (dplyr)


##############################

### dummy data

##############################


coord1 <- c(50, 47, 45)
coord2 <- c(50, 51, 49)
frame <- data.frame(coord1, coord2)
coords <- coordinates(frame)

x = list(1, 2, 3, 4, 5)
y = list(1, 2, 3, 4, 5)

for (i in 1:length(x)) { # create clusters based on coords

set.seed(i+100)
x[[i]] <- rnorm(5000, mean = coords[, 1], sd = 1)
y[[i]] <- rnorm(5000, mean = coords[, 2], sd = 1)
}

obs <- data.frame(x, y)
names(obs) <- c('x1', 'x2', 'x3', 'x4', 'x5', 'y1', 'y2', 'y3', 'y4', 'y5')
coordinates(obs) <- c('x1', 'y1') # this creates a spatial points data frame

# create blank raster of study area

ex <- extent(c(45, 50, 48, 52))
target <- raster(ex, resolution = 0.5)

# create raster brick

r_list <- list()

for (i in 1:ncol(obs)) {

   r_list[[i]] <- rasterize(obs, target, fun = 'count')
}

obs_frequency <- brick(r_list)

这是一种可能但很慢的解决方案

############################

### Example Solution

############################

vals_all <- obs_frequency[, ] ### this is very slow ###
vals_all <- data.frame(vals_all)

### sample values

points <- sample_n(vals_all, size = 5)
points <- t(points)
points <- data.frame(points)
points_tidy <- gather(points)
points_tidy$xval <- rep(1:8, times = 5)


### plot

ggplot(points_tidy, aes(x = xval, y = value)) + geom_line(aes(colour = key)) + theme_classic()

1 个答案:

答案 0 :(得分:1)

我已经找到了使用raster :: extract函数的更好的解决方案。这样可以直接对值进行采样,并避免将整个栅格图块变成破坏内存的矩阵。

值得注意的是,在这里,使用Brick比使用Raster堆栈快得多。

Ñ
相关问题