You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言ggplot2绘制栅格堆栈时筛选pH>5区域并标记低阈值区域为灰色的方法

报错原因与解决方案

你之前执行pfiles <- pfiles1 > 5得到的是逻辑型(TRUE/FALSE)离散栅格,传入连续色阶就会触发Discrete value supplied to continuous scale报错,按以下步骤修改即可实现需求:


第一步:依赖安装与数据预处理

# 新增加载ggnewscale包,用于实现多填充色阶,未安装先执行install.packages("ggnewscale")
library(raster)
library(rasterVis)
library(viridis)
library(ggplot2)
library(ggpubr)
library(ggnewscale)

shp = broom::tidy(shapefile("G:/WB_dist_utm.shp"))
rfiles = list.files(path = "G:/GW_IDW", pattern = "*.tif", full.names = TRUE)
atr = c(paste("Year", sep = "_", seq(2005, 2019, 2)))

pfiles1 = stack(rfiles[c(33:40)])
# 重分类:将≤5的数值设为NA,保留栅格连续数值属性
pfiles <- reclassify(pfiles1, rcl = c(-Inf, 5, NA))
names(pfiles) = atr

第二步:绘图代码修改

ph = gplot(pfiles) + 
  # 底层全栅格填充灰色,对应pH≤5的区域
  geom_raster(fill = "gray70") +
  # 新增独立填充色阶,用于有效pH值的渐变配色
  new_scale_fill() +
  geom_raster(aes(fill = value)) +
  geom_path(data=shp, aes(long, lat, group=group), color = 'black') +
  facet_wrap(~ variable, ncol = 4) +
  # 连续渐变配置,限定最小值为5,NA值设为透明露出底层灰色
  scale_fill_gradientn(colours = rev(magma(30)), 
                       limits = c(5, 8),
                       na.value = "transparent", 
                       n.breaks = 6,
                       guide = guide_colourbar(order = 2)) +
  # 手动添加No Data的灰色图例
  scale_fill_manual(values = "gray70", 
                    labels = "No Data Available",
                    guide = guide_legend(order = 1)) +
  theme_bw() +
  theme(axis.text = element_blank(), legend.position = "right", legend.direction = "vertical",
        axis.title = element_blank(),
        legend.key.height = unit(2, "cm"), legend.key.width = unit(1, "cm"),
        legend.title = element_blank(), legend.text = element_text(size = 26), 
        strip.text = element_text(size = 28, face = "bold"),
        plot.title = element_text(size = 23, face = "bold"),
        plot.subtitle = element_text(size = 15), plot.caption = element_text(size = 10)) +
  labs(title = "Ground Water Quality in West Bengal: 2005 - 2019",
       subtitle = "pH values\n",
       caption = "Data source: ENVIS Centre on Control of Pollution Water, Air and Noise.
       http://www.cpcbenvis.nic.in/water_quality_data.html
       Prepared by: Akhilesh Kumar") +
  coord_equal()

实现效果

  • pH>5的区域正常显示magma渐变配色,渐变范围从5开始符合实际pH区间
  • pH≤5的区域显示为灰色,图例中会单独出现「No Data Available」的灰色条目
  • 不会再出现离散值传入连续色阶的报错

内容的提问来源于stack exchange,提问作者Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:30:04