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

绘制Sentinel2A光谱剖面遇两类R语言绘图错误,求解决方法

问题解决

1. 修复"invalid RGB specification"错误

这个错误是因为颜色代码格式不规范:

  • #fce00 只有5位十六进制字符,RGB颜色需要6位,改为 #fce000
  • ff0000 缺少前缀 #,改为 #ff0000

修正后的颜色向量:

mycolors <- c("#ffbf00", "#bf9000", "#9d5b17", "#fce000", "#56b4e9", "#32410c", "#ff0000", "#808080")

2. 修复"x and y lengths differ"错误

这个错误的核心是lines()函数中x和y的长度不匹配,解决方法如下:

可能原因及修复:

  • 原因1:lines()未明确指定x轴:默认x是1:length(y),但如果初始化空图时的x范围和y的长度不匹配,会触发错误。解决方法是明确指定x轴为波段的位置索引,保证和y的长度完全一致。
  • 原因2:aggregate后列数异常:如果trainingdata中除了cl列还有非数值型列,aggregate的mean函数会自动跳过这些列,导致sp[i,-1]的长度小于ncol(trainingdata)-1。需要确保trainingdata中除cl外的所有列都是数值型的波段反射率数据。

修正后的绘图循环代码:

# Draw one line for each class
for(i in 1:nrow(sp)){
  print(i)
  # 明确指定x轴为1到波段数(即sp的列数减1)
  lines(x = 1:(ncol(sp)-1),
        y = as.numeric(sp[i,-1]),
        lwd = 3,
        col = mycolors[i]
  )
}

完整修正代码

# aggregate cl-column
sp <- aggregate(. ~ cl, data = trainingdata, FUN = mean, na.rm = TRUE)

# Plot empty plot of the defined size
plot(0,
     ylim = c(min(sp[2:ncol(sp)]), max(sp[2:ncol(sp)])),
     xlim = c(1, ncol(sp)-1),  # 这里改为ncol(sp)-1,确保和lines的x范围一致
     type = 'n',
     xlab = "Sentinel2A Bands",
     ylab = "Reflectance [% * 100]"
)

# Define colors for class representation - one color per class!
mycolors <- c("#ffbf00", "#bf9000", "#9d5b17", "#fce000", "#56b4e9", "#32410c", "#ff0000", "#808080")

# Draw one line for each class
for(i in 1:nrow(sp)){
  print(i)
  lines(x = 1:(ncol(sp)-1),
        y = as.numeric(sp[i,-1]),
        lwd = 3,
        col = mycolors[i]
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:40:23