如何在R中生成2001/01-2020/12的时间序列向量并绘制时序图?
生成目标时间序列向量的方法
方法1:使用Base R的seq.Date()
直接生成日期序列,ggplot可自动识别时间类型并优化轴标签显示:
library(tidyverse) # 生成温度数据 df <- tibble(tem = runif(240, 1, 10)) # 生成2001-01到2020-12的月度时间序列 df$time <- seq.Date(from = as.Date("2001-01-01"), by = "month", length.out = 240) # 绘图,自定义x轴显示格式为YYYY/MM ggplot(df, aes(time, tem)) + geom_line() + geom_point() + theme_bw() + scale_x_date(date_labels = "%Y/%m")
方法2:使用lubridate包(tidyverse生态,更简洁)
lubridate是tidyverse的一部分,处理时间逻辑更直观:
library(tidyverse) library(lubridate) df <- tibble(tem = runif(240, 1, 10)) # 从2001年1月开始,生成240个月度时间点 df$time <- ym("2001-01") %>% seq(by = "month", length.out = 240) # 绘图并设置时间轴格式 ggplot(df, aes(time, tem)) + geom_line() + geom_point() + theme_bw() + scale_x_date(date_labels = "%Y/%m")
若需纯字符串格式的时间向量
如果一定要生成"2001/01"这类字符串形式的向量,可通过format()转换:
# 基于已生成的日期序列转换 df$time_str <- format(df$time, "%Y/%m") # 此时time_str即为你需要的c("2001/01", "2001/02", ..., "2020/12")格式
注意:推荐保留Date类型的时间列用于绘图,因为ggplot对时间类型的支持更完善,可轻松调整刻度、范围,而字符串类型需额外处理排序和格式适配。
内容的提问来源于stack exchange,提问作者jackywang
相关产品推荐
相关产品推荐

