加载在线COG栅格后用ggplot2绘制stars对象时维度不匹配报错求助
解决stars加载远程COG后ggplot facet_wrap维度不匹配错误
当使用read_stars通过/vsicurl加载多个远程COG格式栅格,并指定along='depth'合并后,用ggplot2::geom_stars和facet_wrap(~depth)绘图时出现维度不匹配错误:
Error in attributes(.Data) <- c(attributes(.Data), attrib) : dims [product 197152] do not match the length of object [1182912]
数据长度是维度乘积的6倍(对应栅格数量),说明合并后的stars对象维度结构异常。
方案1:关闭proxy模式加载数据
远程COG默认以proxy模式加载(仅存储数据引用,不读取实际内容),这会导致along参数无法正确处理维度合并。关闭proxy模式直接读取数据,可修复维度问题:
library(stars) library(ggplot2) list_ras <- c("SOC_000_005_EV_N_P_AU_TRN_N_20220727.tif", "SOC_005_015_EV_N_P_AU_TRN_N_20220727.tif", "SOC_015_030_EV_N_P_AU_TRN_N_20220727.tif", "SOC_030_060_EV_N_P_AU_TRN_N_20220727.tif", "SOC_060_100_EV_N_P_AU_TRN_N_20220727.tif", "SOC_100_200_EV_N_P_AU_TRN_N_20220727.tif") # 添加proxy=FALSE参数,直接读取完整数据 ras <- read_stars(paste0('/vsicurl/https://esoil.io/TERNLandscapes/Public/Products/TERN/SLGA/SOC/', list_ras), along = 'depth', proxy = FALSE) # 重命名depth维度的取值 levels(ras$depth) <- c("0-5 cm", "5-15 cm", "15-30 cm", "30-60 cm", "60-100 cm", "100-200 cm") ggplot() + geom_stars(data = ras, downsample = 100) + facet_wrap(~depth)
方案2:逐个加载并手动合并(适合大文件)
如果栅格文件过大,关闭proxy模式内存压力大,可逐个加载栅格,手动添加depth维度后合并:
library(stars) library(ggplot2) library(purrr) list_ras <- c("SOC_000_005_EV_N_P_AU_TRN_N_20220727.tif", "SOC_005_015_EV_N_P_AU_TRN_N_20220727.tif", "SOC_015_030_EV_N_P_AU_TRN_N_20220727.tif", "SOC_030_060_EV_N_P_AU_TRN_N_20220727.tif", "SOC_060_100_EV_N_P_AU_TRN_N_20220727.tif", "SOC_100_200_EV_N_P_AU_TRN_N_20220727.tif") depth_names <- c("0-5 cm", "5-15 cm", "15-30 cm", "30-60 cm", "60-100 cm", "100-200 cm") # 逐个加载栅格,为每个栅格添加depth维度 ras_list <- map2(list_ras, depth_names, function(file, name) { s <- read_stars(paste0('/vsicurl/https://esoil.io/TERNLandscapes/Public/Products/TERN/SLGA/SOC/', file)) # 新增depth维度,设置对应名称 st_set_dimensions(s, 3, values = name, name = "depth") }) # 合并所有栅格对象 ras <- do.call(c, ras_list) ggplot() + geom_stars(data = ras, downsample = 100) + facet_wrap(~depth)
问题原因
远程COG的proxy加载模式下,read_stars的along参数无法正确解析多个栅格的维度对齐逻辑,导致合并后的stars对象内部数据长度与维度乘积不匹配(6个栅格的数据被堆叠但维度未正确扩展)。关闭proxy模式或手动控制维度合并,能确保stars对象的结构符合ggplot的解析要求。
内容的提问来源于stack exchange,提问作者Alexandre Wadoux
相关产品推荐
相关产品推荐

