求助:使用gplot/ggplot2绘制RasterBrick时报错的解决方法
问题描述
按照方法将shapefile的每个属性生成栅格文件,得到RasterBrick对象后,用gplot或ggplot2绘制时均报错,重新读取堆叠也无效。
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"’
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")
报错原因分析
gplot报错:gplot是rasterVis的函数,调用时错误使用data =参数传递栅格对象,导致函数无法识别输入类型,触发签名不匹配错误。ggplot2报错:ggplot()仅支持数据框或可被fortify()转换为数据框的对象,而RasterBrick属于S4类对象,无法直接被处理,必须先转换为长格式数据框。
解决方法
方法1:正确调用rasterVis::gplot
移除data =参数,直接将RasterBrick对象传入gplot:
gplot(x) + geom_tile(aes(fill = value)) + facet_wrap(~ variable) + scale_fill_viridis_c() # 可选:添加连续型配色方案
方法2:转换数据格式后用ggplot2绘图
先将RasterBrick转换为长格式数据框,再进行绘图:
# 加载tidyr包用于格式转换 library(tidyr) # 将栅格转换为包含坐标的宽格式数据框 x_df <- as.data.frame(x, xy = TRUE) # 转为长格式 x_long <- pivot_longer(x_df, cols = c(var1, var2), names_to = "variable", values_to = "value") # ggplot2绘图 ggplot(x_long, aes(x = x, y = y, fill = value)) + geom_tile() + facet_wrap(~ variable) + theme_bw() + scale_fill_viridis_c()
如果使用reshape2包替代tidyr,代码如下:
library(reshape2) x_df <- as.data.frame(x, xy = TRUE) x_long <- melt(x_df, id.vars = c("x", "y"), variable.name = "variable", value.name = "value") ggplot(x_long, aes(x, y, fill = value)) + geom_tile() + facet_wrap(~variable) + theme_bw()
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

