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

R语言ggplot2绘制含大量NaN的多列时序折线散点复合图

解决方案

有两种常用的实现方式,你可以根据自己的需求选择:

方案1:不修改原数据结构,直接对每个系列单独过滤

这种方式不需要调整原宽表结构,直接在你原来的基础写法上修改即可,只需要给每个geom_line单独指定过滤了对应列NaN的数据集即可,散点不需要额外处理,NaN值默认不会被绘制:

library(ggplot2)

ggplot(NDVI_sat_h_COR, aes(x = Date)) +
  # meanNDVIU系列
  geom_line(aes(y = meanNDVIU), colour = "blue", 
            data = ~.x[!is.nan(.x$meanNDVIU), ]) +
  geom_point(aes(y = meanNDVIU), colour = "blue") +
  # meanNDVIN系列
  geom_line(aes(y = meanNDVIN), colour = "green", 
            data = ~.x[!is.nan(.x$meanNDVIN), ]) +
  geom_point(aes(y = meanNDVIN), colour = "green") +
  # meanNDVIh系列
  geom_line(aes(y = meanNDVIh), colour = "red", 
            data = ~.x[!is.nan(.x$meanNDVIh), ]) +
  geom_point(aes(y = meanNDVIh), colour = "red") +
  # NDVIL系列
  geom_line(aes(y = NDVIL), colour = "purple", 
            data = ~.x[!is.nan(.x$NDVIL), ]) +
  geom_point(aes(y = NDVIL), colour = "purple") +
  # NDVIM系列
  geom_line(aes(y = NDVIM), colour = "orange", 
            data = ~.x[!is.nan(.x$NDVIM), ]) +
  geom_point(aes(y = NDVIM), colour = "orange") +
  # 统一设置Y轴
  scale_y_continuous(name = "NDVI", limits = c(0.2, 0.8))

注:这里的~.x是ggplot2支持的lambda语法,代表传入的原始数据集,如果你使用的旧版本ggplot不支持,直接替换成NDVI_sat_h_COR即可

方案2:转换为长表格式,代码更简洁易维护

如果你的数值列较多,更推荐把宽表转为tidy长表格式,一次映射就能完成所有系列的绘制,还能自动生成图例:

library(ggplot2)
library(tidyr)
library(dplyr)

# 转换为长格式,过滤所有NaN值
df_long <- NDVI_sat_h_COR %>%
  pivot_longer(cols = -Date, names_to = "NDVI_type", values_to = "NDVI_value") %>%
  filter(!is.nan(NDVI_value))

# 绘图
ggplot(df_long, aes(x = Date, y = NDVI_value, color = NDVI_type)) +
  geom_line() +
  geom_point() +
  scale_y_continuous(name = "NDVI", limits = c(0.2, 0.8)) +
  # 可自定义各系列颜色
  scale_color_manual(values = c(
    "meanNDVIU" = "blue",
    "meanNDVIN" = "green",
    "meanNDVIh" = "red",
    "NDVIL" = "purple",
    "NDVIM" = "orange"
  ))

这种方式后续要新增/删除系列、调整样式都更方便,不需要重复写多次geom层。

内容的提问来源于stack exchange,提问作者Cláudio Siva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:36:01