在时间序列图上更改轴

Changing Axis on Time Series Plot

我根据以下数据框制作了一个时间序列。

     Year    Month Demand
1 2010  January   48.5
2 2010 February   46.0
3 2010    March   54.4
4 2010    April   49.8
5 2010      May   48.1
6 2010     June   55.0

我使用以下方法制作 ts 对象:

   ts.Monthly.Demand=Monthly.Demand%>%
  select(Demand)%>%
  ts(start=2010,frequency=12)

我使用以下内容来制作情节:

ts.Monthly.Demand%>%
  autoplot()

如何将月份添加到 x 轴?

转换为动物园并使用 scale_x_yearmon

library(zoo)

z.Monthly.Demand <- as.zoo(ts.Monthly.Demand)
autoplot(z.Monthly.Demand) + scale_x_yearmon() + xlab("")

给予:

或使用经典图形:

plot(z.Monthly.Demand)

由于 autoplot returns 一个 ggplot 对象,您可以像在任何其他 ggplot 工作流程中一样向其添加额外的 ggplot 函数。这包括设置比例,例如使用 scale_x_date 并根据需要提供日期间隔。 date_labels:

的几个格式选项
library(tidyverse)
library(ggfortify)

ts1 <- df %>%
  select(Demand) %>%
  ts(start = 2010, frequency = 12)

autoplot(ts1) + scale_x_date(date_labels = "%m-%Y")

autoplot(ts1) + scale_x_date(date_labels = "%B %Y")

autoplot(ts1) + scale_x_date(date_labels = "%b '%y")

reprex package (v0.2.0) 创建于 2018-06-13。