Bryan Adams
Bryan Adams

Reputation: 174

Changing Axis on Time Series Plot

I have made a time series from the following dataframe.

     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

I use the following to make the ts object:

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

I use the following to make the plot:

ts.Monthly.Demand%>%
  autoplot()

enter image description here

How can I add the month to the x-axis?

Upvotes: 0

Views: 3157

Answers (2)

camille
camille

Reputation: 16832

Since autoplot returns a ggplot object, you can add additional ggplot functions to it as you would in any other ggplot workflow. That includes setting the scale, such as with scale_x_date and giving date breaks however you like. A couple formatting options to 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")

Created on 2018-06-13 by the reprex package (v0.2.0).

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269481

Convert to zoo and use scale_x_yearmon

library(zoo)

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

giving:

screenshot

or using classic graphics:

plot(z.Monthly.Demand)

screenshot

Upvotes: 2

Related Questions