R语言时间序列数据可视化
知识点总览
- 时间序列数据基础(创建与处理)
- 折线图(ggplot2 + 时间序列)
- 面积图
- 地平线图
- 螺旋图
- 日历图
- 本章小结
1. 时间序列数据基础
核心语法:
ts():创建时间序列对象as.Date()/as.POSIXct():日期转换zoo/xts包:处理不规则时间序列
r
# 加载必要包
library(ggplot2)
library(dplyr)
# 创建示例时间序列数据
# 生成日期序列:2020年1月到2022年12月,每月1日
dates <- seq(as.Date("2020-01-01"), as.Date("2022-12-01"), by = "month")
# 生成随机趋势数据(含季节波动)
set.seed(123) # 固定随机种子,保证结果可重复
n <- length(dates)
trend <- seq(10, 20, length.out = n) # 线性上升趋势
seasonal <- 5 * sin(2 * pi * (1:n) / 12) # 年度季节波动
noise <- rnorm(n, mean = 0, sd = 2) # 随机噪声
value <- trend + seasonal + noise # 合成时间序列
# 存入数据框
df <- data.frame(date = dates, value = value)
# 查看前6行
head(df)
2. 折线图
用途:显示随时间变化的趋势。
核心语法:
geom_line():画折线geom_point():加数据点scale_x_date():格式化日期轴
r
# 绘制基础折线图
ggplot(df, aes(x = date, y = value)) +
geom_line(color = "steelblue", size = 1) + # 折线颜色和粗细
geom_point(color = "red", size = 1.5) + # 添加数据点
labs(
title = "时间序列折线图示例",
subtitle = "2020年1月 - 2022年12月",
x = "日期",
y = "数值"
) +
theme_minimal() + # 简洁主题
scale_x_date(date_breaks = "6 months", # X轴刻度间隔6个月
date_labels = "%Y-%m") + # 日期格式显示
theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转X轴标签
3. 面积图
用途:强调累积量或总量随时间的变化。
核心语法:
geom_area():面积图alpha:透明度
r
# 计算累积和
df <- df %>%
mutate(cumsum_value = cumsum(value))
# 绘制面积图
ggplot(df, aes(x = date, y = cumsum_value)) +
geom_area(fill = "lightblue", alpha = 0.6) + # 填充颜色及透明度
geom_line(color = "darkblue", size = 1) + # 添加边框线
labs(
title = "面积图:累积值变化",
x = "日期",
y = "累积数值"
) +
theme_light() +
scale_x_date(date_breaks = "3 months",
date_labels = "%b %Y") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
4. 地平线图
用途:压缩多个时间序列在窄空间中对比(适合多指标)。
核心语法:
- 需要
ggHorizon包(基于 ggplot2 扩展) - 或手动分箱 + 正负颜色映射
注:地平线图通过将数据分段并折叠成水平带,每个区域用不同颜色表示正负偏差。
安装包:
r
install.packages("ggHorizon")
案例代码:
r
library(ggHorizon)
# 创建多组时间序列数据(模拟不同产品销售额)
set.seed(456)
df_multi <- data.frame(
date = rep(dates, 3),
value = c(value,
value * 0.8 + rnorm(n, 0, 1),
value * 1.2 + rnorm(n, 0, 2)),
group = rep(c("产品A", "产品B", "产品C"), each = n)
)
# 绘制地平线图
ggplot(df_multi, aes(x = date, y = value, fill = group)) +
geom_horizon(bandwidth = 2, # 每个带的数值范围宽度
origin = "midpoint") + # 以中值为基准分正负
facet_grid(group ~ .) + # 纵向分面
scale_fill_brewer(palette = "RdBu") + # 红蓝配色(正负区分)
labs(title = "地平线图:多产品销售额对比",
x = "日期", y = "偏差带") +
theme_minimal() +
theme(legend.position = "bottom")
5. 螺旋图
用途:显示周期性模式(如一天内、一年内),将时间映射到极坐标系螺旋路径。
核心语法:
- 计算角度和半径
coord_polar()或ggplot2+geom_path()
手动实现螺旋图:
r
# 以年周期为例,将日期转换为一年中的第几天
df$day_of_year <- as.numeric(format(df$date, "%j"))
df$year <- as.numeric(format(df$date, "%Y"))
# 计算角度(0~360°对应全年天数)
df$angle <- 2 * pi * (df$day_of_year / 365)
# 半径随年份增加(螺旋外扩)
df$radius <- df$year - min(df$year) + 1
# 绘制螺旋图
ggplot(df, aes(x = radius * cos(angle), y = radius * sin(angle), color = value)) +
geom_path(size = 1.2) +
geom_point(size = 2) +
scale_color_gradient(low = "blue", high = "red") +
coord_fixed() + # 保持圆形比例
labs(title = "时间序列螺旋图(年度周期 + 逐年上升)",
color = "数值") +
theme_void() + # 隐藏坐标轴
theme(legend.position = "right")
解释:螺旋图将时间卷成螺旋,内圈为早,外圈为晚,颜色表示数值大小。
6. 日历图
用途:按日历月/周展示数据(如每日温度、股票收盘价)。
核心语法:
ggplot2+ 按星期几和月份排布- 或使用
ggcal/calendR包
手动构建日历图:
r
# 生成每日数据(完整年份)
daily_dates <- seq(as.Date("2021-01-01"), as.Date("2021-12-31"), by = "day")
daily_values <- rnorm(length(daily_dates), mean = 50, sd = 15)
df_daily <- data.frame(
date = daily_dates,
value = daily_values
)
# 提取星期几(0=周日)和 月份周数
df_daily$weekday <- as.numeric(format(df_daily$date, "%w"))
df_daily$week_of_year <- as.numeric(format(df_daily$date, "%U"))
df_daily$month <- as.numeric(format(df_daily$date, "%m"))
# 绘制类似 GitHub 贡献图的日历
ggplot(df_daily, aes(x = weekday, y = -week_of_year, fill = value)) +
geom_tile(color = "white", size = 0.5) + # 方格
facet_wrap(~ month, scales = "free_y", ncol = 3) + # 按月份分面
scale_fill_gradient2(low = "green", mid = "yellow", high = "red",
midpoint = mean(daily_values)) +
labs(title = "日历图:2021年每日数值分布",
x = "星期几(周日=0)", y = "周数(负序)", fill = "数值") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 90))
7. 本章小结
| 图表类型 | 适用场景 | 关键语法 |
|---|---|---|
| 折线图 | 趋势变化 | geom_line() |
| 面积图 | 累积量 / 总量变化 | geom_area() |
| 地平线图 | 多序列紧凑对比 | geom_horizon() |
| 螺旋图 | 周期性 + 长期趋势 | 极坐标 + 路径 |
| 日历图 | 按日历格展示每日数据 | geom_tile() + 分面 |