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

如何在R中绘制图表展示多站点干旱期与间隔期的时间序列数据?

按站点绘制干旱期与间隔期的R实现方案

问题描述

我在R中拥有一个包含三个站点干旱数据的data.frame:

Droughts <- data.frame("site_id" = c(1,1,1,2,2,2,2,3,3),
                       "Drought_start" = c(1962,1970,1980,1960,1970,1978,1990,1965,1988),
                       "Drought_end" = c(1964,1975,1984,1964,1974,1980,1993,1980,1993))

需要绘制一张图表,按站点分别展示干旱期及其之间的间隔期,但不清楚这类图表的具体名称,无法调研实现方法。

实现步骤

1. 数据预处理

原始数据仅包含干旱期,我们需要补充计算各站点干旱之间的间隔期数据:

library(dplyr)
library(tidyr)

# 按站点分组,整理并生成间隔期数据
Droughts_full <- Droughts %>%
  group_by(site_id) %>%
  arrange(Drought_start) %>%
  # 获取前一次干旱的结束时间
  mutate(prev_drought_end = lag(Drought_end)) %>%
  # 计算间隔期的起止年份
  mutate(gap_start = prev_drought_end + 1,
         gap_end = Drought_start - 1) %>%
  # 将干旱期和间隔期数据格式统一
  pivot_longer(cols = c(Drought_start:Drought_end, gap_start:gap_end),
               names_to = c("period_type", ".value"),
               names_pattern = "(.*)_(start|end)") %>%
  # 过滤无效的间隔期(比如首个干旱期前无间隔,或起止时间不合法)
  filter(!is.na(start) & start <= end) %>%
  # 给时期类型设置易懂标签
  mutate(period_type = ifelse(period_type == "Drought", "干旱期", "间隔期")) %>%
  ungroup()

2. 绘制时间轴矩形图

使用ggplot2的geom_rect绘制矩形来代表不同时期,按站点区分y轴位置,按时期类型区分颜色:

library(ggplot2)

ggplot(Droughts_full, 
       aes(xmin = start, xmax = end, 
           ymin = site_id - 0.3, ymax = site_id + 0.3,
           fill = period_type)) +
  geom_rect(color = "black") +
  # 配置坐标轴
  scale_x_continuous(name = "年份", breaks = seq(1960, 1995, 5)) +
  scale_y_continuous(name = "站点ID", breaks = unique(Droughts$site_id)) +
  # 设置时期颜色
  scale_fill_manual(values = c("干旱期" = "#d73027", "间隔期" = "#1a9850")) +
  # 优化主题样式
  theme_minimal() +
  theme(legend.title = element_blank(),
        panel.grid.major.y = element_blank())

运行上述代码后,会生成一张按站点垂直排列的时间轴图表,每个站点对应行中,红色矩形代表干旱期,绿色矩形代表干旱间隔期,清晰展示各时期的时间范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:10:17