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

ggplot栅格叠加矢量绘图报错:颜色编码需为正数

解决方案

核心问题分析

报错的根源在于:

  1. 使用了new_scale_color()重置颜色(轮廓)美学,但两个图层均使用**fill(填充)**美学,该函数无法重置fill尺度,导致前后两个fill尺度冲突;
  2. 矢量图层可能继承了栅格图层的x/y美学属性,引发不必要的映射干扰。

修正后的代码

library(ggplot2)
library(ggnewscale)  # 确保加载该包以使用new_scale_fill()
library(raster)
library(sf)

# 加载数据
data_vector <- st_read("~/Desktop/TramsTenes2.gpkg")
orto <- brick("~/Desktop/of25mtif1676931256706.tif")
names(orto) <- c("r", "g", "b")
orto_df <- as.data.frame(orto, xy = TRUE)

# 合并绘制图层
ggplot() +
  # 绘制RGB栅格
  geom_raster(
    data = orto_df,
    aes(x = x, y = y, fill = rgb(r = r, g = g, b = b, maxColorValue = 255)),
    show.legend = FALSE
  ) +
  scale_fill_identity() +
  # 重置fill美学尺度,为矢量图层准备独立的fill映射
  new_scale_fill() +
  # 绘制矢量图层,禁用继承美学属性
  geom_sf(
    data = data_vector,
    aes(fill = Seccio),
    lwd = 0.001,
    inherit.aes = FALSE
  ) +
  scale_fill_identity()

额外检查项

如果仍报错,请确认:

  • 栅格与矢量图层的坐标系(CRS)一致。可通过crs(orto)查看栅格CRS,用st_transform(data_vector, crs = crs(orto))转换矢量图层坐标系;
  • Seccio列的值为有效的颜色编码(如十六进制字符串、颜色名称或正整数索引)。

内容的提问来源于stack exchange,提问作者Oriol Baena Crespo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:47:48