如何将spplot的点状图例改为色阶图例(基于INLA预测绘图)
解决spplot图例显示为点状而非连续色阶的问题
你的猜测完全正确——问题根源在于Sbiomass的数据类型:如果该列是因子(factor),spplot会默认生成离散的点状图例;只有当它是**数值型(numeric)**时,才会渲染你需要的连续色阶条。
具体修改步骤:
强制转换数据类型为数值型
在给region.grid_sf$Sbiomass赋值时,显式用as.numeric()确保变量类型正确,避免因原有列类型导致的强制转换:# 替换原赋值代码 region.grid_sf$Sbiomass <- as.numeric(m_grid$summary.fitted.values[index.pred, "mean"]) region.grid_sf$Sbiomass_sd <- as.numeric(m_grid$summary.fitted.values[index.pred, "sd"])调整spplot参数,指定连续色阶逻辑
添加at参数定义色阶的分割区间(可根据你的数据范围调整),同时通过colorkey参数明确渲染色阶条:my.palette <- brewer.pal(n = 7, name = "OrRd") # 生成色阶分割点(示例:从Sbiomass最小值到最大值,分成6个间隔,对应7种颜色) biomass_range <- range(region.grid_sf$Sbiomass, na.rm = TRUE) color_breaks <- seq(biomass_range[1], biomass_range[2], length.out = length(my.palette)) par(mar = c(0,0,0,0)) spplot(region.grid_sf, zcol = "Sbiomass", # 明确指定数值列 col.regions = my.palette, col = "transparent", at = color_breaks, # 指定色阶分割点 colorkey = list(space = "right", # 色阶条显示在右侧 labels = list(at = color_breaks, # 色阶条刻度 cex = 0.8))) # 刻度文字大小
补充方案(可选):
如果你的region.grid_sf是sf对象,也可以用ggplot2替代spplot,语法更直观且图例控制更灵活:
library(ggplot2) ggplot(region.grid_sf) + geom_sf(aes(fill = Sbiomass), color = "transparent") + scale_fill_gradientn(colors = my.palette) + theme_void()
内容的提问来源于stack exchange,提问作者CharlotteS.
相关产品推荐
相关产品推荐

