如何调整fpp3包autoplot()生成图表的x轴日期格式为仅显示年份
你可以直接在现有绘图代码后追加scale_x_date()层自定义x轴日期格式,即可实现仅显示年份的需求,完整可运行代码如下:
# 加载必要包(如已加载可省略) library(fpp3) library(ggplot2) # 原有数据处理逻辑不变 melsyd_economy <- ansett %>% filter(Airports == "MEL-SYD", Class == "Economy") %>% mutate(Passengers = Passengers/1000) # 绘图时新增scale_x_date层调整x轴格式 autoplot(melsyd_economy, Passengers) + scale_x_date(date_labels = "%Y", date_breaks = "1 year") + labs(title = "Ansett airlines economy class", subtitle = "Melbourne-Sydney", y = "Passengers ('000)", x = "年份")
参数说明:
date_labels = "%Y":指定x轴刻度标签仅展示4位年份,如需其他格式可替换格式符,比如%Y年%m月会显示为1989年01月date_breaks = "1 year":指定x轴刻度间隔为1年,若觉得刻度过密可改为"2 years"实现隔年显示
如果你的数据是周度专属的yearweek类型索引,也可以使用适配的轴设置实现同样效果:
autoplot(melsyd_economy, Passengers) + scale_x_yearweek(labels = ~ lubridate::year(.x), breaks = "1 year") + labs(title = "Ansett airlines economy class", subtitle = "Melbourne-Sydney", y = "Passengers ('000)")
内容的提问来源于stack exchange,提问作者Blake Shurtz
相关产品推荐
相关产品推荐

