我按照这个答案为 shapefile 中的每个属性创建了光栅文件,最后得到了一个 RasterBrick。但是当我尝试使用
gplot
或 ggplot2
绘制它时,它会抛出错误。我尝试再次读取文件然后堆叠它,但错误是一样的。
创建栅格的链接:https://stackoverflow.com/a/47664716/11696009
使用时出错
gplot
:
> gplot(data = x) + geom_tile(aes(fill = value)) + facet_wrap(~ variable)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘gplot’ for signature ‘"missing"’
With
ggplot2
它抛出以下错误:
> ggplot(data = x) + geom_tile(aes(fill = value)) + facet_wrap(~ variable) + theme_bw()
Error in `fortify()`:
! `data` must be a <data.frame>, or an object coercible by `fortify()`, not an S4 object with class <RasterBrick>.
Run `rlang::last_error()` to see where the error occurred.
请帮我解决这个问题,或者至少是这个错误的原因是什么。
library(raster)
library(rasterVis)
library(ggplot2)
r <- raster(ncols=36, nrows=18)
p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
att <- data.frame(id=1:3, var1=10:12, var2=c(6,9,6))
pols <- spPolygons(p1, p2, p3, attr=att)
pols$id <- 1:nrow(pols)
r <- rasterize(pols, r, field='id')
x <- subs(r, data.frame(pols), by='id', which=2:ncol(pols), filename="rstr.grd")
如错误所述,“'data' 必须是 data.frame,或由
fortify()
强制的对象,而不是具有类 RasterBrick 的 S4 对象”。这意味着 ggplot2
无法解释 RasterBrick。你必须把它转换成ggplot2
可以处理的东西,比如数据框:
library(raster)
library(ggplot2)
library(tidyverse)
# Convert RasterBrick created by your example code to dataframe
df <- as.data.frame(x, xy = TRUE)
由于我对 RasterBrick 对象不是不熟悉,所以我不确定您要提取哪些变量。我假设“df”数据框中的默认“var1”和“var2”值表示相同的东西,所以我已经旋转 df,所以“var1”和“var2”都在同一列中。如果这不合适,请省略下一步。请注意,如果您确实跳过
pivot_longer()
步骤,则在ggplot()
代码中将对“value”的两个引用更改为“var1”或“var2”:
df <- df %>% pivot_longer(!c(x, y))
现在绘制 df:
ggplot(df, aes(x, y)) +
geom_tile(aes(fill = value), show.legend = FALSE) +
facet_wrap(~ value) +
theme_bw()
这可能不是您想要的,但它应该可以帮助您解决问题。