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

使用ggplot堆叠绘制滑雪季各年度雪高度时序演化图遇问题求助

问题分析

空图的核心原因有两个:

  1. Date_without_year是字符串类型,ggplot会按字母顺序排序(比如04-01会排在12-01前面),导致时间轴顺序完全混乱,geom_area无法正确识别连续的时间序列。
  2. geom_area默认需要明确的分组逻辑,且你用color仅设置了线条颜色,没有设置填充色(堆叠区域需要填充色区分不同赛季)。
解决步骤

1. 预处理数据:构建正确的滑雪季时间轴

我们需要把Date_without_year转换为可排序的连续时间标识,两种可行方法:

方法1:转换为固定年份的日期对象

选一个闰年(比如2020年)来构建日期,确保能覆盖所有可能的日期:

library(dplyr)
library(lubridate)

DAll <- DAll %>%
  mutate(Season_Date = as.Date(paste("2020", Date_without_year, sep = "-")))

方法2:计算滑雪季内的天数

从12月1日开始计数,得到每个日期在滑雪季的连续天数:

DAll <- DAll %>%
  mutate(
    temp_date = as.Date(paste("2020", Date_without_year, sep = "-")),
    Day_in_Season = as.integer(temp_date - as.Date("2020-12-01")) + 1
  ) %>%
  select(-temp_date)

2. 绘制堆叠面积图

使用处理后的时间轴,设置fill=Season区分赛季,同时调整参数确保堆叠正常:

用固定年份日期作为X轴

library(ggplot2)

plot <- ggplot(DAll, aes(x = Season_Date, y = SnowHeight, fill = Season)) +
  geom_area(position = "stack", alpha = 0.7) + # alpha调整透明度,避免重叠过暗
  scale_x_date(
    date_labels = "%m-%d", # 仅显示月-日格式
    breaks = seq(as.Date("2020-12-01"), as.Date("2021-04-30"), by = "1 month") # 按月设置刻度
  ) +
  labs(x = "Date (Dec-Apr)", y = "Snow Height", title = "Snow Height Evolution by Ski Season") +
  theme_minimal()
print(plot)

用滑雪季天数作为X轴

plot <- ggplot(DAll, aes(x = Day_in_Season, y = SnowHeight, fill = Season)) +
  geom_area(position = "stack", alpha = 0.7) +
  scale_x_continuous(
    breaks = c(1, 31, 60, 91, 121, 151), # 对应12/01、01/01等关键日期的天数
    labels = c("12-01", "01-01", "02-01", "03-01", "04-01", "04-30")
  ) +
  labs(x = "Date (Dec-Apr)", y = "Snow Height", title = "Snow Height Evolution by Ski Season") +
  theme_minimal()
print(plot)
额外补充
  • 如果部分日期在某些赛季无数据,会导致堆叠中断,可使用tidyr::complete()补全缺失值(填充0或NA),确保每个日期对应所有赛季都有数据点。
  • 若不想堆叠而是重叠展示,将position = "stack"改为position = "identity"即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:45:24