如何在ggplot与dplyr中操作tsibble的yearmonth类型数据
操作tsibble的yearmonth类型实现数据筛选或x轴范围限制
你可以根据需求选择两种实现方案:
方案1:提前筛选数据集,仅保留2000年及之后的数据
yearmonth是tsibble封装的有序时间类型,支持直接的大小比较,筛选可以用两种写法:
- 直接构造yearmonth类型的阈值做比较
library(fpp3) Data <- aus_retail %>% filter(State == "Western Australia", Industry == "Takeaway food services", Month >= yearmonth("2000 Jan")) # 绘图默认展示筛选后的数据 autoplot(Data)
- 提取年份字段做判断
library(fpp3) library(lubridate) Data <- aus_retail %>% filter(State == "Western Australia", Industry == "Takeaway food services", year(Month) >= 2000) autoplot(Data)
方案2:不修改原数据集,绘图时直接限制x轴范围
如果不需要改动原数据,仅需要调整可视化的x轴范围,给xlim()传入yearmonth类型的起止值即可:
library(fpp3) Data <- aus_retail %>% filter(State == "Western Australia", Industry == "Takeaway food services") # 限制x轴范围为2000年1月到2020年1月,可根据需求调整起止值 autoplot(Data) + xlim(yearmonth("2000 Jan"), yearmonth("2020 Jan"))
注意:不要直接传入字符串作为xlim()的参数,必须转为和x轴变量一致的yearmonth类型,否则会出现类型不匹配的报错
内容的提问来源于stack exchange,提问作者Kyle Mouly
相关产品推荐
相关产品推荐

