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

请求绘制分年代分组的月尺度流量对比折线图(含RCP情景)

实现按年代分组的月份-流量折线图(ggplot2)

1. 数据预处理

先给数据添加年代分组列,将年份映射到目标区间:

library(tidyverse)

# 假设你的数据框名为flow_data,包含Year、Month、Type、Flow列
flow_data <- flow_data %>%
  mutate(
    Decade = case_when(
      Year >= 2030 & Year <= 2040 ~ "2030-2040",
      Year >= 2041 & Year <= 2050 ~ "2041-2050",
      Year >= 2051 & Year <= 2060 ~ "2051-2060",
      TRUE ~ NA_character_
    )
  ) %>%
  drop_na(Decade) # 移除不在目标年代区间的行

2. 完整绘图代码

参考目标多面板样式,通过facet_wrap实现年代分组,同时区分三种流量类型的折线:

ggplot(flow_data, aes(x = Month, y = Flow, color = Type, group = Type)) +
  # 绘制折线与散点,增强可读性
  geom_line(linewidth = 1) +
  geom_point(size = 2, alpha = 0.7) +
  # 按年代分面板,可根据需求调整行列数
  facet_wrap(~Decade, nrow = 3) +
  # 自定义颜色映射,匹配观测/模拟数据的常规配色
  scale_color_manual(
    values = c(
      "Observed" = "#000000",
      "RCP 4.5 Simulated" = "#2196F3",
      "RCP 8.5 Simulated" = "#F44336"
    )
  ) +
  # 设置坐标轴与标题
  labs(
    x = "Month",
    y = "Streamflow",
    color = "Data Type",
    title = "Monthly Streamflow by Decade and Scenario"
  ) +
  # 优化主题样式
  theme_bw() +
  theme(
    strip.text = element_text(face = "bold", size = 10),
    legend.position = "bottom",
    axis.title = element_text(face = "bold"),
    axis.text.x = element_text(angle = 45, hjust = 1) # 避免月份标签重叠
  )

关键细节调整

  • 若Month是数值型(1-12),可添加scale_x_continuous(breaks = 1:12)强制显示所有月份;若为字符型(Jan-Dec),ggplot会自动按顺序排列。
  • 需要每个年代面板Y轴独立缩放时,在facet_wrap中加入scales = "free_y"。
  • 可根据实际需求修改linewidth、size、颜色值等参数,匹配目标图表样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:12:19