R语言时间序列图X轴:将小数格式改为年月格式的方法
解决R语言时间序列预测图X轴显示小数的问题
错误原因
你遇到的axis.Date报错,是因为该函数要求at参数必须是Date类对象,但time(myTimeSeries)返回的是ts对象的时间数值(例如2022.9167代表2022年11月),无法直接转换为Date类型,因此触发错误。
方法一:基于原代码修改(保留forecast包绘图)
将ts的时间数值转换为Date格式,然后手动替换X轴标签:
library(tsibble) library(forecast) # 创建tsibble myTsibble <- tsibble( YearMonth = seq(yearmonth("2022-11"), length.out = 12, by = 1), Value = c(3, 2, 1, 4, 4, 3, 6, 5, 7, 10, 7, 8), index = YearMonth ) # 转换为ts对象 myTimeSeries <- ts( myTsibble$Value, frequency = 12, start = c(year(min(myTsibble$YearMonth)), month(min(myTsibble$YearMonth))) ) # 将ts时间值转为Date格式 ts_dates <- as.Date(yearmonth(time(myTimeSeries))) # 绘制预测图,关闭默认X轴后添加自定义轴 mySes <- ses(myTimeSeries) plot(mySes, main = "Item ABC", ylab = "Units Sold", xlab = "Year Month", xaxt = "n") axis(1, at = time(myTimeSeries), labels = format(ts_dates, "%b %Y"))
方法二:使用tsibble + fable包(更简洁的tidy流程)
既然你已经使用了tsibble,推荐直接用fable包处理预测,它会自动识别时间索引并生成正确的年月格式轴,无需手动调整:
library(tsibble) library(fable) library(ggplot2) # 创建tsibble myTsibble <- tsibble( YearMonth = seq(yearmonth("2022-11"), length.out = 12, by = 1), Value = c(3, 2, 1, 4, 4, 3, 6, 5, 7, 10, 7, 8), index = YearMonth ) # 拟合SES模型并生成预测(h为预测周期数,可自行调整) mySes <- myTsibble %>% model(SES = ETS(Value ~ error("A") + trend("N") + season("N"))) %>% forecast(h = 3) # 自动生成带年月格式X轴的预测图 mySes %>% autoplot(myTsibble) + labs(title = "Item ABC", y = "Units Sold", x = "Year Month") + theme_minimal()
说明
- 方法一适合习惯使用
forecast包原生绘图的场景,通过转换时间格式手动替换轴标签; - 方法二更符合tidy时间序列的工作流,无需在ts和tsibble之间来回转换,绘图时自动适配时间索引格式。
内容的提问来源于stack exchange,提问作者Cytosis
相关产品推荐
相关产品推荐

